Video in progress
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:
Collectionitself has no general rule.ArrayDeque,PriorityQueueandConcurrentLinkedQueuedon't overrideObject.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 aListand compare those.map.values()usesObject.equalstoo:m1.values().equals(m2.values())is almost alwaysfalse.- If a
TreeSet's comparator is inconsistent withequals, the result oftreeSet.equals(hashSet)can depend on which side you call it from, becausecontainsAlluses each side's own notion of equality. - Arrays themselves are compared by reference in
equals, so you needArrays.equals.
In tests, AssertJ's containsExactly (with order) and containsExactlyInAnyOrder show the intent more clearly, and the failure message is easier to read too.
Sign up to mark studied questions and save your progress.