TreeSet原理与源码分析

TreeSet 原理与源码分析

1、原理

2、源码分析

2.1、构造方法

1
2
3
4
//底层采用TreeMap实现
public TreeSet(Comparator<? super E> comparator) {
this(new TreeMap<>(comparator));
}

2.2、构造方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//由于其底层采用TreeMap实现,其底层方法同样使用TreeMap的方法
//TreeSet只采用TreeMap存放key的一列,与HashSet相似
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
public boolean contains(Object o) {
return m.containsKey(o);
}
public boolean isEmpty() {
return m.isEmpty();
}
public int size() {
return m.size();
}
public boolean remove(Object o) {
return m.remove(o)==PRESENT;
}
public void clear() {
m.clear();
}