public class BigD{
public static void main(String[] args) {
List<Employee> emps = new ArrayList<Employee>();
emps.add(new Employee("Bal", "5"));
emps.add(new Employee("Kiri", "7"));
emps.add(new Employee("Pad", "2"));
Map tree = new TreeMap();
for(int i=0; i<emps.size(); i++) {
Employee emp = null;
emp = emps.get(i);
System.out.println("hashcode : " + emp.hashCode());
tree.put(emp, emp.getFirstNM()); // why is not keeping all three elements here ?
}
System.out.println(tree.size()); //why does it print the size as "1"
}
}
class Employee implements Comparable {
private String firstNM;
private String lastNM;
Employee(String firstNM, String lastNM) {
this.firstNM = firstNM;
this.lastNM = lastNM;
}
public String getFirstNM() {
return firstNM;
}
public void setFirstNM(String firstNM) {
this.firstNM = firstNM;
}
public String getLastNM() {
return lastNM;
}
public void setLastNM(String lastNM) {
this.lastNM = lastNM;
}
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
}
Please let me know
why the treemap “tree” has just one element which is of employee object “Pad”, even though all three Employee objects which I am adding are having different hashcodes.
Is it because of I am not overriding equals/hashcode? if yes – why should I override when all are returning different hashcodes
Your thoughts would be appreciated.
Thanks
The problem is that when you put objects into the treemap, the treeMap uses employee.comparedTo method to see if you are inputting a new key. Since defined the comparedTo method to return 0 everytime (which means the two objects are the same), the treeMap will think that you are pairing different Employee value with the same key object every time you call treeMap.put. If you change the comparedTo to return -1, or appropriate value reflecting the order of the objects, then the treeMap.size() will return 3.