When two collections are equal
Compare collections across implementations and know exactly when equals says false.
Open this lesson in the learning hubKey points
- Two
Lists are equal when they hold equal elements in the same order — the implementation is irrelevant. - An
ArrayListcan equal aLinkedList, but aListis never equal to aSet. - Two
Sets are equal when they hold the same elements — order plays no part at all. - Two
Maps are equal when theirentrySets are equal, so aTreeMapcan equal aHashMap. - Arrays compare by identity:
a.equals(b)is false for equal contents. UseArrays.equalsinstead. - All of it rests on the elements: one broken
equalsand every answer above is meaningless.
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Integer> arrayList = new ArrayList<>(List.of(1, 2, 3));
List<Integer> linkedList = new LinkedList<>(List.of(1, 2, 3));
System.out.println("ArrayList = LinkedList : " + arrayList.equals(linkedList) + " (same elements, same order)");
System.out.println("same hashCode : " + (arrayList.hashCode() == linkedList.hashCode()));
System.out.println("order matters : " + arrayList.equals(List.of(3, 2, 1)));
Set<Integer> hashSet = new HashSet<>(List.of(1, 2, 3));
Set<Integer> treeSet = new TreeSet<>(List.of(3, 2, 1));
System.out.println("HashSet = TreeSet : " + hashSet.equals(treeSet) + " (order is irrelevant for sets)");
System.out.println("List = Set : " + arrayList.equals(hashSet) + " (different contracts)");
Map<String, Integer> hashMap = new HashMap<>(Map.of("x", 1, "y", 2));
Map<String, Integer> treeMap = new TreeMap<>(Map.of("y", 2, "x", 1));
System.out.println("HashMap = TreeMap : " + hashMap.equals(treeMap) + " (same entrySet)");
int[] p = {1, 2, 3};
int[] q = {1, 2, 3};
System.out.println("p.equals(q) : " + p.equals(q) + " (arrays compare by identity)");
System.out.println("Arrays.equals(p, q) : " + Arrays.equals(p, q));
System.out.println("List.of(p) vs List.of(q): " + List.of(p).equals(List.of(q)) + " (one array each)");
System.out.println("contains uses equals : " + List.of("a", "b").contains(new String("b")));
}
}
Collections compare on contract and contents, never on class. Arrays compare on neither.
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Collections course, and every lesson in it is listed on the Collections contents page.