Advanced Java: Collections, Generics and More ยท Ordering and Equality
Why does a HashSet keep two "identical" objects? Because without equals and hashCode, Java only compares identity.
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());
}
}main. args holds its command-line arguments (none here). plains is created on the stack and points to a new HashSet on the heap: [].Plain constructor to set up the new object, with id = 1.Plain() has finished, so its variables are gone.plains points to.Plain() has finished, so its variables are gone.plains points to.propers is created on the stack and points to a new HashSet on the heap: [].Proper constructor to set up the new object, with id = 1.Proper() has finished, so its variables are gone.hashCode(). It gets its own variables on the stack.propers.add(new Proper(1)).Proper constructor to set up the new object, with id = 1.Proper() has finished, so its variables are gone.hashCode(). It gets its own variables on the stack.equals(), with o = {id: 1}. It gets its own variables on the stack. hashCode() has finished, so its variables are gone.propers.add(new Proper(1)); // equal: not added again.2 1.