I am confused with below piece of code. When i changed the the name for employee e2 i was expecting the map to have both e2 and e3 objects as the e2 object is now different than e3. But it seems changing the name for e2 object is not reflected in the e2 object stored in hashmap so the output shows only e3. So i am confused whether the hashmap stores the actual object or just the copy of the original object.
Code:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Employee,Integer> map = new HashMap<Employee,Integer>();
Employee e1 = new Employee(10,"Sachin");
Employee e2 = new Employee(10,"Sachin");
map.put(e1, 1);
map.put(e2,2);
System.out.println(e1.hashCode()+" "+e2.hashCode());
System.out.println(map);
e2.setName("Akshay"); //<---- changing the name for e2
Employee e3 = new Employee(10,"Sachin");
map.put(e3, 3);
System.out.println(map);
}
}
class Employee
{
private int id;
private String name;
public Employee(int id, String name) {
super();
this.id = id;
this.name = 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;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
Output:
-1826112337 -1826112337
{Employee [id=10, name=Sachin]=2}
{Employee [id=10, name=Sachin]=3}