liveBook · Manning

Arrays.equals

As explained in 100 Java Mistakes and How to Avoid Them

Arrays.equals is a Java utility method that tests whether two arrays have equal lengths and pairwise equal elements.

Avoid using equals() to compare Java arrays by content: arrays inherit Object.equals(), which compares identity like == rather than elements. section 7.2

Compare array contents explicitly

int[] first = {1, 2, 3}; int[] second = {1, 2, 3}; first.equals(second); // false Arrays.equals(first, second); // true Arrays.deepEquals(matrix1, matrix2); // nested arrays section 7.2

Choose the comparison deliberately:

  • Use Arrays.equals() for ordinary arrays and Arrays.deepEquals() for nested arrays. section 7.2
  • Do not generalize equals() as a reliable content comparison; several JDK types also retain identity-style behavior. section 7.2

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains the identity mechanism and contrasts Arrays.equals() with Arrays.deepEquals(), without detailing implementation internals.
Examples
Uses ordinary arrays and nested arrays to contrast identity comparison with content comparison.
What it assumes
Assumes familiarity with Java objects, references, equals(), and the == operator.
What you can do after
Apply Arrays.equals() or Arrays.deepEquals() instead of equals() when comparing array contents.
How it connects
Connects array comparison with equals(), ==, Object.equals(), and Arrays.deepEquals().

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.