|
| 1 | +package learnCollections; |
| 2 | + |
| 3 | +import java.util.HashMap; |
| 4 | +import java.util.Map; |
| 5 | +import java.util.Objects; |
| 6 | + |
| 7 | +public class HashCodeAndEqualsMethod { |
| 8 | + public static void main(String[] args) { |
| 9 | + HashMap<Person, String> map = new HashMap<>(); |
| 10 | + Person p1 = new Person("Alice", 1); |
| 11 | + Person p2 = new Person("Bob", 2); |
| 12 | + Person p3 = new Person("Alice", 1); // same content as p1 but different object -> diff memory -> diff hashcode |
| 13 | + |
| 14 | + map.put(p1, "Engineer"); // hashcode1 --> index1 |
| 15 | + map.put(p2, "Designer"); // hashcode2 --> index2 |
| 16 | + map.put(p3, "Manager"); // hashcode3 --> index3 |
| 17 | + |
| 18 | + System.out.println("HashMap Size: " + map.size()); // 3 because p1 and p3 are different objects (different hashcodes) even though they have same content |
| 19 | + System.out.println("Value for p1: " + map.get(p1)); // Engineer |
| 20 | + System.out.println("Value for p3: " + map.get(p3)); // Manager |
| 21 | + |
| 22 | + // After overriding equals() and hashCode() in Person class, p1 and p3 are considered equal (same content) and will have same hashcode, so p3 will replace p1's value in the map |
| 23 | + // HashMap Size: 2 |
| 24 | + // Value for p1: Manager |
| 25 | + // Value for p3: Manager |
| 26 | + |
| 27 | + |
| 28 | + Map<String, Integer> map1 = new HashMap<>(); |
| 29 | + map1.put("Shubham", 90); // hashcode1 --> index1 |
| 30 | + map1.put("Neha", 92); // hashcode2 --> index2 |
| 31 | + map1.put("Shubham", 99); // hashcode1 --> index1 --> equals() --> replace |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +class Person { |
| 36 | + String name; |
| 37 | + int id; |
| 38 | + |
| 39 | + public Person(String name, int id) { |
| 40 | + this.name = name; |
| 41 | + this.id = id; |
| 42 | + } |
| 43 | + |
| 44 | + public String getName() { |
| 45 | + return name; |
| 46 | + } |
| 47 | + |
| 48 | + public int getId() { |
| 49 | + return id; |
| 50 | + } |
| 51 | + |
| 52 | + @Override |
| 53 | + public boolean equals(Object o) { |
| 54 | + if (this == o) return true; |
| 55 | + if (o == null || getClass() != o.getClass()) return false; |
| 56 | + |
| 57 | + Person person = (Person) o; |
| 58 | + return id == person.getId() && Objects.equals(name, person.getName()); |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public int hashCode() { |
| 63 | + return Objects.hash(name, id); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public String toString() { |
| 68 | + return "id: " + id + ", name: " + name; |
| 69 | + } |
| 70 | +} |
0 commit comments