0

If I have an Employee class and used as a key in HashMap and if I am using same variables for both object then how map finds duplicate key?

public class Employee {

    int id;
    String name;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

Main class

public class EmployeeTest {

    public static void main(String[] args) {
        Employee e1 = new Employee();
        e1.setId(100);
        e1.setName("abc");
        Employee e2 = new Employee();
        e2.setId(100);
        e2.setName("xyz");
        Map<Employee, Integer> map = new HashMap<Employee, Integer>();
        map.put(e1, 1);
        map.put(e2, 2);
    }
    
}

Is e2 a duplicate object or adding new entry in map?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
ravi
  • 11
  • 2
  • 1
    You need to correctly implement `hashCode()` and `equals()` in your `Employee` class. – Robby Cornelissen Jan 19 '23 at 05:01
  • @dantiston In this case, it's not a duplicate key. Without a proper `hashCode()`/`equals()` implementation, these two `Employee` objects will be inserted as two separate keys. – Robby Cornelissen Jan 19 '23 at 05:08
  • please please please do try to avoid using objects as keys in HashMaps. your Employee object has an ID field, which is probably unique, and you can use it as a key to map an integer to an employee. – Tom Elias Jan 19 '23 at 06:59
  • @RobbyCornelissen the OP literally asked about duplicate keys. I understand that since `equals` and `hashCode` aren’t implemented, they will be inserted as separate entries, but that’s the result of the current implementation. The answers to the linked question directly answer “is e2 a duplicate object or adding a new entry in map.” – dantiston Jan 20 '23 at 06:45

0 Answers0