== compares references. equals() compares content.
Analogy: == = same person? equals() = same info?
==:
equals():
==.1String s1 = new String("hello");2String s2 = new String("hello");3s1 == s2; // FALSE4s1.equals(s2); // TRUE56String s3 = "hello";7String s4 = "hello";8s3 == s4; // TRUE (pool)9s3.equals(s4); // TRUE1011int a = 5, b = 5;12a == b; // TRUE
Override 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 age == other.age && Objects.equals(name, other.name);11 }1213 @Override14 public int hashCode() {15 return Objects.hash(name, age);16 }17}1819Person p1 = new Person("Alice", 30);20Person p2 = new Person("Alice", 30);21p1.equals(p2); // TRUE
Must override hashCode() with equals():
1Set<Person> set = new HashSet<>();2set.add(new Person("Alice", 30));3set.add(new Person("Alice", 30));4set.size(); // 1 (with hashCode), 2 (without — WRONG)
Mistakes: Using == for objects, equals() on primitives, forgetting hashCode().