Equals or hashCode on arrays¶
ID: java/equals-on-arrays
Kind: problem
Security severity:
Severity: error
Precision: very-high
Tags:
- quality
- reliability
- correctness
Query suites:
- java-security-and-quality.qls
Click to see the query in the CodeQL repository
The equals and hashCode methods on arrays only consider object identity, not array contents, which is unlikely to be what is intended.
Recommendation¶
To compare the lengths of the arrays and the corresponding pairs of elements in the arrays, use one of the comparison methods from java.util.Arrays:
The method
Arrays.equalsperforms a shallow comparison. That is, array elements are compared usingequals.The method
Arrays.deepEqualsperforms a deep comparison, which is appropriate for comparisons of nested arrays. Similarly,Arrays.hashCodeandArrays.deepHashCodecan be used to compute shallow and deep hash codes based on the hash codes of individual array elements.
Example¶
In the following example, the two arrays are first compared using the Object.equals method. Because this checks only reference equality and the two arrays are different objects, Object.equals returns false. The two arrays are then compared using the Arrays.equals method. Because this compares the length and contents of the arrays, Arrays.equals returns true.
public void arrayExample(){
String[] array1 = new String[]{"a", "b", "c"};
String[] array2 = new String[]{"a", "b", "c"};
// Reference equality tested: prints 'false'
System.out.println(array1.equals(array2));
// Equality of array elements tested: prints 'true'
System.out.println(Arrays.equals(array1, array2));
}
References¶
Java API Specification: Arrays.equals, Arrays.deepEquals, Objects.deepEquals, Object.equals, Arrays.hashCode, Arrays.deepHashCode, Object.hashCode.