web123456

TreeMap implements custom sorting through Comparator/Comparable

public V put(K key, V value) { Entry<K,V> t = root; if (t == null) { compare(key, key); // type (and possibly null) check root = new Entry<>(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) { //If the comparator is not empty, then the size of the key is compared by the comparator do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) // The comparison result is less than 0, and placed in the left child node t = t.left; else if (cmp > 0) // The comparison result is greater than 0 and placed in the right child node t = t.right; else return t.setValue(value); // The result is equal to zero, which means that the key values ​​are equal, overriding the value value } while (t != null); } else { // When no Comparator is passed, use the compareTo method of the key object if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") 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<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }