2
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;
    }
}

请让我知道为什么树形图“树”只有一个元素是员工对象“Pad”,即使我添加的所有三个员工对象都具有不同的哈希码。是因为我没有覆盖等于/哈希码吗?如果是 - 当所有人都返回不同的哈希码时,我为什么要覆盖您的想法将不胜感激。谢谢

4

2 回答 2

9

compareTo()因为您在方法中比较每个对象相同

  public int compareTo(Object o) {
        // TODO Auto-generated method stub
        return 0;
    }

让它像

public int compareTo(Object o) {
      return ((this.getFirstName() + this.getLastName()).compareTo((o.getFirstName() + o.getLastName())));
}

这将表示如果两个人的名字和姓氏相同,那么他们是相等的,我建议你有一个人 ID 字段来区分

因此,当它尝试添加另一个实例时,它会发现它与 Key Setof 中已添加的实例相同Map

使 compareTo 实现正确也覆盖 equals()方法

于 2012-06-12T09:09:10.213 回答
3

问题是当您将对象放入树形图中时,树形图使用 employee.comparedTo 方法来查看您是否正在输入新键。由于定义了 compareTo 方法每次都返回 0(这意味着两个对象相同),因此每次调用 treeMap.put 时,treeMap 都会认为您将不同的 Employee 值与相同的键对象配对。如果您将 compareTo 更改为返回 -1 或反映对象顺序的适当值,则 treeMap.size() 将返回 3。

于 2012-06-12T09:24:19.497 回答