GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • CodeQL documentation
  • CodeQL overview
  • Writing CodeQL queries
  • CodeQL language guides
  • QL language reference
  • CodeQL standard-libraries
  • CodeQL query help
  • CodeQL repository
  • QL publications
  • CodeQL query help for C and C++
  • CodeQL query help for C#
  • CodeQL query help for GitHub Actions
  • CodeQL query help for Go
  • CodeQL query help for Java and Kotlin

This view

  • Original page
  • New address

GeezerVison is showing codeql.github.com — Equals or hashCode on arrays — CodeQL query help documentation

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:

  • The method Arrays.equals performs a shallow comparison. That is, array elements are compared using equals.

  • The method Arrays.deepEquals performs a deep comparison, which is appropriate for comparisons of nested arrays. Similarly, Arrays.hashCode and Arrays.deepHashCode can 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.

  • © GitHub, Inc.
  • Terms
  • Privacy
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.