Search code examples
javacollectionstreemap

TreeMap returns null while using map.get(Object)


TreeMap prints value as null while fetching value using get method whereas it is working fine with HashMap(). Please find below the sample code and provide inputs to this.

It's working fine for Hashmap as it uses equals()/hashcode() methods whereas TreeMap are SortedMap, it doesn't use equals method to compare two objects. Instead, it uses comparator/comparable to compare the objects but while fetching the object using get method, it's giving null as response. Please provide some clarity here.

    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));**
    }
}

Solution

  • Your compareTo method always returns 1, which means no Employees object is equal to any other Employees object (not even to itself) as far as compareTo is concerned.

    Only when compareTo returns 0 the two compared instances are considered identical by TreeMap.

    BTW, your hashCode implementation of always returning 1 is also bad. While it works (for HashMap), it causes all the entries to be stored in the same bucket, which destroys the performance of the HashMap.