Search code examples
javatreemap

Why firstEntry() is not the first entry of a map?


public static void main(String[] args) {
    TreeMap<Integer,Integer>map=new TreeMap<>();
    map.put(1,2);
    Map.Entry<Integer, Integer> e = map.higherEntry(0);
    System.out.println(e==map.firstEntry());
}

The entry of e and map.firstEntry() is both (1,2), but they are not the same since the System.out.println() function will print false. I am really confused.

I want to get a true.


Solution

  • As stated in the comments, you have to compare them by using equals (e.equals(map.firstEntry())).

    It is because it wraps the map entry in a new AbstractMap.SimpleImmutableEntry for each of the two calls. Hence the two references of the Map.Entry (e and map.firstEntry() in your code) are different, but they are equal.

    Here's the source code of TreeMap's higherEntry and firstEntry.

    public Map.Entry<K,V> higherEntry(K key) {
        return exportEntry(getHigherEntry(key));
    }
    
    public Map.Entry<K,V> firstEntry() {
        return exportEntry(getFirstEntry());
    }
    

    The exportEntry static method wraps the TreeMap.Entry in a new SimpleImmutableEntry object.

    static <K,V> Map.Entry<K,V> exportEntry(TreeMap.Entry<K,V> e) {
        return (e == null) ? null :
            new AbstractMap.SimpleImmutableEntry<>(e);
    }