Advanced Java: Collections, Generics and More ยท Ordering and Equality

equals and hashCode

Why does a HashSet keep two "identical" objects? Because without equals and hashCode, Java only compares identity.

EqualsHashCodeDemo.java

import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

class Plain {
    int id;
    Plain(int id) { this.id = id; }
}

class Proper {
    int id;
    Proper(int id) { this.id = id; }

    @Override
    public boolean equals(Object o) {
        return o instanceof Proper p && p.id == id;
    }

    @Override
    public int hashCode() {
        return Objects.hash(id);
    }
}

public class EqualsHashCodeDemo {
    public static void main(String[] args) {
        Set<Plain> plains = new HashSet<>();
        plains.add(new Plain(1));
        plains.add(new Plain(1));          // looks the same, but counts as different
        Set<Proper> propers = new HashSet<>();
        propers.add(new Proper(1));
        propers.add(new Proper(1));        // equal: not added again
        System.out.println(plains.size() + " " + propers.size());
    }
}

Step by step

  1. The program starts in main. args holds its command-line arguments (none here). plains is created on the stack and points to a new HashSet on the heap: [].
  2. Java runs the Plain constructor to set up the new object, with id = 1.
  3. Plain() has finished, so its variables are gone.
  4. a Plain is added to the end of the HashSet that plains points to.
  5. A second Plain(1). Without equals/hashCode, Java treats it as a different object, so the set keeps both.
  6. Plain() has finished, so its variables are gone.
  7. a Plain is added to the end of the HashSet that plains points to.
  8. propers is created on the stack and points to a new HashSet on the heap: [].
  9. Java runs the Proper constructor to set up the new object, with id = 1.
  10. Proper() has finished, so its variables are gone.
  11. Java calls hashCode(). It gets its own variables on the stack.
  12. Proper.hashCode: built from id, so equal objects get equal hashes.
  13. Line runs: propers.add(new Proper(1)).
  14. Java runs the Proper constructor to set up the new object, with id = 1.
  15. Proper() has finished, so its variables are gone.
  16. Java calls hashCode(). It gets its own variables on the stack.
  17. Java calls equals(), with o = {id: 1}. It gets its own variables on the stack. hashCode() has finished, so its variables are gone.
  18. Same hash, so the set calls equals: the ids match, so it is a duplicate.
  19. Line runs: propers.add(new Proper(1)); // equal: not added again.
  20. It prints 2 1.
  21. 2 versus 1. Only the class with equals and hashCode recognised its duplicate.