首页 > 代码库 > java 17 - 6 TreeSet集合及其add()方法的源码解析

java 17 - 6 TreeSet集合及其add()方法的源码解析

  TreeSet:能够对元素按照某种规则进行排序。
    排序有两种方式
    A:自然排序
    B:比较器排序

  TreeSet集合的特点:排序和唯一

 1 public class TreeSetDemo { 2 public static void main(String[] args) { 3 // 创建集合对象 4 // 自然顺序进行排序 5 TreeSet<Integer> ts = new TreeSet<Integer>(); 6  7 // 创建元素并添加 8 // 20,18,23,22,17,24,19,18,24 9 ts.add(20);10 ts.add(18);11 ts.add(23);12 ts.add(22);13 ts.add(17);14 ts.add(24);15 ts.add(19);16 ts.add(18);17 ts.add(24);18 19 // 遍历20 for (Integer i : ts) {21 System.out.println(i);22 }23 }24 }

 


通过观察TreeSet的add()方法,我们知道最终要看TreeMap的put()方法。

TressSet集合的add()方法的源码:

 

 1 interface Collection {...} 2  3 interface Set extends Collection {...} 4  5 interface NavigableMap { 6  7 } 8  9 class TreeMap implements NavigableMap {10 public V put(K key, V value) {11 Entry<K,V> t = root;12 if (t == null) {13 compare(key, key); // type (and possibly null) check14 15 root = new Entry<>(key, value, null);16 size = 1;17 modCount++;18 return null;19 }20 int cmp;21 Entry<K,V> parent;22 // split comparator and comparable paths23 Comparator<? super K> cpr = comparator;24 if (cpr != null) {25 do {26 parent = t;27 cmp = cpr.compare(key, t.key);28 if (cmp < 0)29 t = t.left;30 else if (cmp > 0)31 t = t.right;32 else33 return t.setValue(value);34 } while (t != null);35 }36 else {37 if (key == null)38 throw new NullPointerException();39 Comparable<? super K> k = (Comparable<? super K>) key;40 do {41 parent = t;42 cmp = k.compareTo(t.key);43 if (cmp < 0)44 t = t.left;45 else if (cmp > 0)46 t = t.right;47 else48 return t.setValue(value);49 } while (t != null);50 }51 Entry<K,V> e = new Entry<>(key, value, parent);52 if (cmp < 0)53 parent.left = e;54 else55 parent.right = e;56 fixAfterInsertion(e);57 size++;58 modCount++;59 return null;60 }61 }62 63 class TreeSet implements Set {64 private transient NavigableMap<E,Object> m;65 66 public TreeSet() {67 this(new TreeMap<E,Object>());68 }69 70 public boolean add(E e) {71 return m.put(e, PRESENT)==null;72 }73 }74 75 真正的比较是依赖于元素的compareTo()方法,而这个方法是定义在 Comparable里面的。76 所以,你要想重写该方法,就必须是先 Comparable接口。这个接口表示的就是自然排序。77 78  

 

TreeSet存储元素自然排序和唯一的图解

技术分享

 

java 17 - 6 TreeSet集合及其add()方法的源码解析