使用 map.get(Object) 时 TreeMap returns null

TreeMap returns null while using map.get(Object)

TreeMap 在使用 get 方法获取值时将值打印为 null,而它在 HashMap() 中工作正常。请在下面找到示例代码并为此提供输入。

Hashmap 工作正常,因为它使用 equals()/hashcode() 方法,而 TreeMap 是 SortedMap,它不使用 equals 方法比较两个对象。相反,它使用 comparator/comparable 来比较对象,但是在使用 get 方法获取对象时,它给出 null 作为响应。请在此处提供一些说明。

    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.TreeMap;

    class Employees implements Comparable<Employees>, Comparator<Employees> {

        public Employees(String name, int id) {
            super();
        this.name = name;
        this.id = id;
    }

    private String name;
    private int id;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (!(obj instanceof Employees))
            return false;
        Employees other = (Employees) obj;
        if (id != other.id)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        return 1;
    }

    @Override
    public int compareTo(Employees o) {
        return 1;
    }

    @Override
    public int compare(Employees o1, Employees o2) {
        return 1;
    }
}

public class Employee {

    public static void main(String[] args) {
        // Map<Employees, Integer> m = new HashMap<>(); // equals will be used here.
        Map<Employees, Integer> m = new TreeMap<Employees, Integer>(); // no equals/hashcode used here as we use comparator/comparable to compare objects.
        Employees e1 = new Employees("abc", 11);
        Employees e2 = new Employees("abc", 12);
        System.out.println(m.put(e1, 1));
        System.out.println(m.put(e2, 2));
        **System.out.println(m.get(e2));**
    }
}

你的 compareTo 方法总是 returns 1,这意味着没有 Employees 对象等于任何其他 Employees 对象(甚至不等于它本身)就 compareTo 而言。

仅当 compareTo returns 0 两个比较实例被 TreeMap 认为相同时。

顺便说一句,您的 hashCode 始终返回 1 的实现也很糟糕。虽然它有效(对于 HashMap),但它会导致所有条目都存储在同一个桶中,这会破坏 HashMap.

的性能