TreeMap

xiaoxiao2021-02-28  93

1.类声明:

//可排序的map,基于红黑树的NavigableMap实现,可以根据键的自然顺序(键可以实现Comparable接口排序)进行排序,也可以根据传入的Comparator进行排序,有Comparator时Comparator优先。 public class TreeMap<K,V> extends AbstractMap<K,V> implements NavigableMap<K,V>, Cloneable, java.io.Serializable {}

2.变量:

//传入的比较器 private final Comparator<? super K> comparator; //树的根节点 private transient Entry<K,V> root;

3.方法:

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) { do { parent = t; cmp = cpr.compare(key, t.key);//key不能为null if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } else {//根据key的Comparable比较 if (key == null) throw new NullPointerException(); @SuppressWarnings("unchecked") Comparable<? super K> k = (Comparable<? super K>) key; do { parent = t; cmp = k.compareTo(t.key);//要进行比较,key不能为null 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; }
转载请注明原文地址: https://www.6miu.com/read-85335.html

最新回复(0)