hashSet 特点:基于Hash表实现,元素唯一不可重复(重写hashCode和equal方法)
TreeSet 特点:基于红黑树(平衡二叉树),元素唯一且有序
源码分析:
HashSet hs = new HashSet();
hs.add("sss");
1--------------------------------------------------------创建对象
public HashSet() {
map = new HashMap<>();
}
public HashSet(Collection extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}
public HashSet(int initialCapacity, float loadFactor) {
map = new HashMap<>(initialCapacity, loadFactor);
}
public HashSet(int initialCapacity) {
map = new HashMap<>(initialCapacity);
}
hashSet底层是HashMap()管理。
2------------------------------------------------------------添加元素
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
private static final Object PRESENT = new Object(); 常量对象
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
Node[] tab;
Node p;
int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length; //首次创建时会走这个流程
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) {
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
TreeSet ts = new TreeSet();
ts.add("sss");
1-------------------------------------------------------------创建对象
public TreeSet() {
this(new TreeMap());
}
public TreeSet(Comparator super E> comparator) {
this(new TreeMap<>(comparator));
}
public TreeSet(Collection extends E> c) {
this();
addAll(c);
}
public TreeSet(SortedSet s) {
this(s.comparator());
addAll(s);
}
底层是TreeMap存储数据
2----------------------------------------------添加元素
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
public final V put(K key, V value) {
if (!inRange(key))
throw new IllegalArgumentException("key out of range");
return m.put(key, value);
}
public V put(K key, V value) {
TreeMapEntry t = root;
if (t == null) {
compare(key, key); // type (and possibly null) check
root = new TreeMapEntry<>(key, value, null);
size = 1;
modCount++;
return null;
}
int cmp;
TreeMapEntry 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);
}
TreeMapEntry e = new TreeMapEntry<>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}
内部实现Comparator保证大小有序(平衡二叉树,大的放右边,小的放左边 )
2种实现方式
2.1给set构造方法传一个比较器
public TreeMap(Comparator super K> comparator) { this.comparator = comparator; }
2.2让存储的自定义数据实现Comparator接口重写comparto()方法
为了方便自己理解, 故做此笔记,如有问题,请多多指教。
此处推荐大牛的讲解,更清楚https://juejin.im/user/57890289a633bd00585c3999