Video in progress

Strong Middle 🧺 Collections

Is new ArrayList<>(x).equals(new LinkedList<>(x)) true? What about HashSet and TreeSet, or a List and a Set? What is the equals contract for collections?

Lists are equal if they have the same elements in the same order, regardless of implementation. Sets are equal if they have the same elements (order doesn't matter), and Maps if they have the same pairs. But a List is never equal to a Set, and for queues there is no general rule.

📖 Answer

var src = List.of(1, 2, 3);
new ArrayList<>(src).equals(new LinkedList<>(src));     // true
new HashSet<>(src).equals(new TreeSet<>(src));          // true
new ArrayList<>(src).equals(new HashSet<>(src));        // false
Map.of("a", 1).equals(new TreeMap<>(Map.of("a", 1)));   // true

The contract is written at the interface level: List.equals compares element by element in order, Set.equals requires equal size and containsAll, and Map.equals requires equal entrySet()s. hashCode is defined to match: for a List, the formula 31 * h + e.hashCode(); for a Set, the sum of the elements' hashes. That is why you can use a List as a HashMap key, as long as it doesn't change.

The traps:

  • Collection itself has no general rule. ArrayDeque, PriorityQueue and ConcurrentLinkedQueue don't override Object.equals, so two queues with the same contents are not equal. In a test, assertEquals(expectedDeque, actualDeque) always fails; you need to convert the contents to a List and compare those.
  • map.values() uses Object.equals too: m1.values().equals(m2.values()) is almost always false.
  • If a TreeSet's comparator is inconsistent with equals, the result of treeSet.equals(hashSet) can depend on which side you call it from, because containsAll uses each side's own notion of equality.
  • Arrays themselves are compared by reference in equals, so you need Arrays.equals.

In tests, AssertJ's containsExactly (with order) and containsExactlyInAnyOrder show the intent more clearly, and the failure message is easier to read too.