In Java, treeset has a question about null key addition.

Source: Internet
Author: User

In treemap, The get (object) method call is entry <K, V> getentry (Object key)

This method throws an exception if key = NULL, so note that when adding a comparator, if the comparator is not empty, it is inserted according to the comparison result of the comparator, if the Insert key is empty

In this case, it is a direct exception. Why? Because treemap is a red-black tree structure, its structure is established based on the sort of key values, the reason why the comparator is not empty does not throw an exception because

The comparator may be compared with null, so the node key in the tree may be null, And if key = NULL is used as the root node, it will be inserted directly and will not be compared.

Note that, for example, if the key in the fruit tree is null, getentry (object) is called when the get (object) method is executed. Let's take a look at the getentry (object) source code:

 final Entry<K,V> getEntry(Object key) {        // Offload comparator-based version for sake of performance        if (comparator != null)            return getEntryUsingComparator(key);        if (key == null)            throw new NullPointerException();Comparable<? super K> k = (Comparable<? super K>) key;        Entry<K,V> p = root;        while (p != null) {            int cmp = k.compareTo(p.key);            if (cmp < 0)                p = p.left;            else if (cmp > 0)                p = p.right;            else                return p;        }        return null;    }
 final Entry<K,V> getEntryUsingComparator(Object key) {K k = (K) key;        Comparator<? super K> cpr = comparator;        if (cpr != null) {            Entry<K,V> p = root;            while (p != null) {                int cmp = cpr.compare(k, p.key);                if (cmp < 0)                    p = p.left;                else if (cmp > 0)                    p = p.right;                else                    return p;            }        }        return null;    }

It can be seen that there are two types of Obtaining Methods: one is if the comparator is empty, the other is not empty, and if the comparator is empty, get (null) will Directly exception,

Therefore, after the comparator is null and null is inserted as the root node, it is impossible to retrieve the value of key = NULL.

The following is the insert algorithm. As for the insert of the red/black tree, I will not elaborate on it here.

 public V put(K key, V value) {        Entry<K,V> t = root;        if (t == null) {    // TBD:    // 5045147: (coll) Adding null to an empty TreeSet should    // throw NullPointerException    //    // compare(key, key); // type check            root = new Entry<K,V>(key, value, null);            size = 1;            modCount++;            return null;        }        int cmp;        Entry<K,V> parent;        // split comparator and comparable paths        Comparator<? super K> cpr = comparator;        if (cpr != null) {            do {                parent = t;                cmp = cpr.compare(key, t.key);                if (cmp < 0)                    t = t.left;                else if (cmp > 0)                    t = t.right;                else                    return t.setValue(value);            } while (t != null);        }        else {            if (key == null)                throw new NullPointerException();            Comparable<? super K> k = (Comparable<? super K>) key;            do {                parent = t;                cmp = k.compareTo(t.key);                if (cmp < 0)                    t = t.left;                else if (cmp > 0)                    t = t.right;                else                    return t.setValue(value);            } while (t != null);        }        Entry<K,V> e = new Entry<K,V>(key, value, parent);        if (cmp < 0)            parent.left = e;        else            parent.right = e;        fixAfterInsertion(e);        size++;        modCount++;        return null;    }

Treemap tree = new treemap (); tree. put (null, 1); system. out. println (tree. size (); system. out. println (tree. get (null); // throws an exception

Custom Comparator

Package trees; import static Java. lang. system. out; import Java. util. treemap; import Java. util. comparator; public class treemaptest {public static void main (string ARGs []) {treemap <integer, integer> tree = new treemap <integer, integer> (new COM ()); tree. put (1, 1); tree. put (null, 2); system. out. println (tree. size (); // 2system. out. println (tree. get (null); // no exception} class com implements comparator <integer >{@ overri Depublic int compare (integer O1, integer O2) {If (O1 = NULL & O2 = NULL) return 0; If (O1! = NULL) return 1; if (O2! = NULL) Return-1; return o1.compareto (O2 );}}


Therefore, when using treeset

In the comparator method int compare (O1, O2), if the relationship between O1, O2 and null is not determined, tree may be generated. put (null, 1) cannot get (null) after saving

For example, we only use the simple if (O1 = NULL | O2 = NULL) Return-1;

After tree. Put (); tree. Put (null, 2), the value of tree. Get (null) will be null.

After talking so much, just one sentence,

If you want to store the key = NULL in the treeset, You need to customize the comparactor, and specify all the relationships between O1, O2, and null in the Custom comparactor.

If you do not customize comparactor, do not store null values.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.