← 返回首页
Equals or hashCode on arrays — CodeQL query help documentation CodeQL docs
CodeQL documentation
CodeQL resources

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-code-quality.qls - 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:

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