内容随时更新,最大程度的分析每个方法
Set 1、TreeSet1、不可以重复储存相同的数据
2、低层的数据结构是一个红黑树
基本用法:
@Test
public void treeSetTest() {
//使用空参构造器,创建TreeSet 容器
TreeSet integers = new TreeSet();
//储存储存数据
for (int i = 0; i < 10; i++) {
integers.add(i + 1);
}
//再添加相同的数据,判断是否可以储存相同的数据
System.out.println(integers.add(10));//false 表明储存不成功
//使用迭代器取出数据
Iterator iterator = integers.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next()+" ");//总的输出结果:1 2 3 4 5 6 7 8 9 10
}
}
构造方法:
查看源码可能发现,创建一个TreeSet集合用4种创建方法
方法源码:
| boolean | add(E e) 将指定的元素添加到此 set(如果该元素尚未存在于 set 中)。 |
| boolean | addAll(Collection extends E> c) 将指定 collection 中的所有元素添加到此 set 中。 |
1、查看add源码:
public boolean add(E e) {
return m.put(e, PRESENT)==null;//这里的PRESENT是一个Object对象,传入储存的数据和Object对象调用Map 接口的put方法形成映射
}
//注意:这里的put方法是TreeMap类的put方法
public V put(K key, V value) {
Entry 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 parent;
// split comparator and comparable paths
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 e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
2、跟进源码put
public V put(K key, V value) {
Entry t = root;//赋值操作,
if (t == null) {
compare(key, key); // type (and possibly null) check(这里检查,查看key是否为null,若为null则扔出空指异常)
root = new Entry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
Entry parent;
// split comparator and comparable paths
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 e = new Entry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
2.1、put方法里面Entry
通过查看Entry
源码跟进,查看setValue方法,对储存的相同数据处理的情况



