When two collections are equal

Collections · lesson 35 of 42 · 3 min read

Compare collections across implementations and know exactly when equals says false.

Open this lesson in the learning hub

Key points

  • Two Lists are equal when they hold equal elements in the same order — the implementation is irrelevant.
  • An ArrayList can equal a LinkedList, but a List is never equal to a Set.
  • Two Sets are equal when they hold the same elements — order plays no part at all.
  • Two Maps are equal when their entrySets are equal, so a TreeMap can equal a HashMap.
  • Arrays compare by identity: a.equals(b) is false for equal contents. Use Arrays.equals instead.
  • All of it rests on the elements: one broken equals and 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.