import java.util.*;
class Data
{
int num;
String name;
Data(String na)
{
name=na;
}
public int hashCode()
{
return 5;
}
public boolean equals(Object o)
{
if(o instanceof Data && ((Data)o).name==this.name)
return true;
else
return false;
}
}
public class Sandeep {
public static void main(String[] args)
{
HashMap map=new HashMap();
Data d1=new Data("Aditya");
Data d2=new Data("Aditya");
map.put(d1,"abc");
map.put(d2,"abcd");
System.out.println(map.get(d1));
System.out.println(map.get(d2));
System.out.println(map.size());
System.out.println(d1 + " " +d2);
}
}
O/Pl;
abcd
1
Data@5 Data@5
I have two duplicate objects. When i put these two objects in a hashmap only one of the object is going to d map(i.e.d2) but when i try to get the value corresponding to d1 key i get the value that of d2. Can you explain why??