== compares references. equals() compares content.
Analogy: == asks "are these the same person?" equals() asks "do they have the same info?"
== operator:
equals() method:
==.1String s1 = new String("hello");2String s2 = new String("hello");3s1 == s2; // FALSE — different objects4s1.equals(s2); // TRUE — same content56String s3 = "hello";7String s4 = "hello";8s3 == s4; // TRUE — same pool object9s3.equals(s4); // TRUE — same content1011// Primitives:12int a = 5, b = 5;13a == b; // TRUE
Overriding equals() correctly:
1class Person {2 private String name;3 private int age;45 @Override6 public boolean equals(Object obj) {7 if (this == obj) return true;8 if (obj == null || getClass() != obj.getClass()) return false;9 Person other = (Person) obj;10 return this.age == other.age11 && Objects.equals(this.name, other.name);12 }1314 @Override15 public int hashCode() {16 return Objects.hash(name, age);17 }18}1920Person p1 = new Person("Alice", 30);21Person p2 = new Person("Alice", 30);22p1 == p2; // FALSE23p1.equals(p2); // TRUE
Critical rule: Override hashCode() when you override equals(). Equal objects must have equal hash codes.
1// WRONG: equals() without hashCode()2Set<Person> set = new HashSet<>();3set.add(new Person("Alice", 30));4set.add(new Person("Alice", 30));5set.size(); // 2 — WRONG! Should be 167// RIGHT: with hashCode()8Set<Person> set2 = new HashSet<>();9set2.add(new Person("Alice", 30));10set2.add(new Person("Alice", 30));11set2.size(); // 1 — correct
Common mistakes:
== for object comparison (use equals()).equals() on primitives (use ==).hashCode() when overriding equals().null in equals().