LinkedHashSet
- LinkedHashSet是HashSet的子类,实现了Set接口
- LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组+双向链表
- LinkedHashSet根据元素的HashCode值来决定元素的存储位置,同时使用链表维护元素的次序,这使得元素看起来是以插入的顺序保存的
- 不允许添加重复元素
Set set = new LinkedHashSet();
set.add(new String("AA"));
set.add(456);
set.add(456);
set.add(new Employee("刘",1001));
set.add(123);
set.add("hello")
1)在LinkedHashSet中维护了一个hash表和双向链表(LinkedHashSet有head和tail)
底层是LinkedHashMap,HashMap的子类
2)每个结点有before和after属性,这样可以形成双向链表
3)在添加一个元素时,先求hash值,再求索引,确定该元素在table的位置,然后将添加的元素加入到双向链表,如果已经存在,就不添加,和HashSet一样。
head指向第一个结点,tail指向最后一个结点
示意代码:
tail.next = newElement;
newElement.pre = tail;
tail = newElement;
4)这样以后,遍历LinkedHashSet也能确保插入顺序和遍历顺序一样
5)第一次添加元素时,直接将table数组扩容到16,存放的结点类型为LinkedHashMap$Entry
6)数组table是HashMap$Node[ ],存放的元素/数据是LinkedHashMap $Entry类型
Entry类型,继承关系,构成多态数组
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}