目录
TreeSet基本介绍


TreeSet基本用法
使用无参构造器创建TreeSet对象
public class TreeSet_ {
public static void main(String[] args) {
TreeSet treeSet = new TreeSet();
treeSet.add("jack");
treeSet.add("roy");
treeSet.add("alisa");
treeSet.add("cecil");
System.out.println(treeSet);
}
}
[alisa, cecil, jack, roy]
使用有参构造器创建TreeSet对象
public class TreeSetSortable {
public static void main(String[] args) {
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
return ((String) o1).compareTo(((String) o2));
}
});
treeSet.add("jack");
treeSet.add("roy");
treeSet.add("alisa");
treeSet.add("cecil");
System.out.println(treeSet);
}
}
[alisa, cecil, jack, roy]
TreeSet源码剖析
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
compare(key, key);
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry<K,V> parent;
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();
@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;
}