I have a custom class that has overridden hashcode()
and equals()
method
class Employee1 {
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Employee1(int id) {
super();
this.id = id;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee1 other = (Employee1) obj;
if (id != other.id)
return false;
return true;
}
}
and in main class I am using a Map
having Object
as Key
Map<Integer,Employee1> g = new HashMap<>();
Employee1 e = new Employee1(1);
Employee1 e1 = new Employee1(2);
g.put(1, e);
g.put(2, e1);
Employee1 e4 = g.get(1);
e4.setId(3);
for(Map.Entry<Integer,Employee1> e3:g.entrySet()) {
System.out.println(e3.getKey()+" "+e3.getValue().getId());
}
My question is how come the key of the map is changed even though I have overridden hashcode
and equals
methods,key should be same but I am able to get and set the id and its reflecting in the map
The output for above code is
1 3 2 2