Equals or hashCode on arrays¶
ID: java/equals-on-arraysKind: problemSecurity severity: Severity: errorPrecision: very-highTags: - quality - reliability - correctnessQuery suites: - java-security-and-quality.qls
Click to see the query in the CodeQL repository
Theequals andhashCode 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 fromjava.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 theObject.equals method. Because this checks only reference equality and the two arrays are different objects,Object.equals returnsfalse. The two arrays are then compared using theArrays.equals method. Because this compares the length and contents of the arrays,Arrays.equals returnstrue.
publicvoidarrayExample(){String[]array1=newString[]{"a","b","c"};String[]array2=newString[]{"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.