Java put method what is the purpose to call compare with itself

Viewed 79

I was reading java source code of TreeMap, for the put method, when the map is empty, it still calling compare key with itself, what is the purpose of that? '''

public V put(K key, V value) {
        TreeMap.Entry<K, V> t = this.root;
        if (t == null) {
            this.compare(key, key);
            this.root = new TreeMap.Entry(key, value, (TreeMap.Entry)null);
            this.size = 1;
            ++this.modCount;
            return null;
        }

'''

1 Answers

Checks.

Specifically, the compare method will toss both the first and second argument (in this case, it's the same thing) at the comparator if it is defined. In which case, if there's a problem with the comparator (for example, the comparator you fed to the TreeMap is designed to compare strings, but it's a map of integers - remember, TreeMap predates generics, there is no guarantee that key is of the correct type) - then this will throw an exception now.

That's a good thing - you want exceptions to occur as early as possible.

Even if there is no comparator defined (i.e. you're going by natural sorting order), this will then cast the key to Comparable, which will throw a ClassCastException if it does not implement the method.

Finally, if you're attempting to add null to the treemap and the comparator doesn't like it (or it's a comparator-less TreeMap), then you get an NPE.

TL;DR: The compare() call either does nothing, or throws an exception, which is the point: Throw early.

Related