Java集合之LinkedHashSet类详解
作者:Neo丶
这篇文章主要介绍了Java集合之LinkedHashSet类详解,LinkedHashSet 是 Java 中的一个集合类,它是 HashSet 的子类,并实现了 Set 接口,与 HashSet 不同的是,LinkedHashSet 保留了元素插入的顺序,并且具有 HashSet 的快速查找特性,需要的朋友可以参考下
LinkedHashSet类
LinkedHashSet是HashSet的子类;
LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组+双向链表;
LinkedHashSet根据元素的hashCode值来决定元素的存储位置,同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的;
- 在LinkedHashSet中维护了一个hash表和双向链表(LinkedHshSet有head和tail);
- 每一个节点有pre和next属性,这样可以形成双向链表;
- 在添加一个元素时,先求hash值,再求索引,确定该元素在hashtable的位置,然后将添加的元素加入到双向链表(如果已经存储过相同元素,则不再添加,原则和HashSet相同)
tail.next = newElement; //简单指定 newElement.pre = tail; tail = newElement; //重置tail,为添加下一个元素做准备
- 遍历LinkedHashSet能确保插入循序和遍历顺序一致。
LinkedHashSet不允许添加重复元素。
底层源码分析
测试代码
package com.pero.set_; import java.util.Iterator; import java.util.LinkedHashSet; /** * LinkedHashSet的底层运行机制 * * @author Pero * @version 1.0 */ @SuppressWarnings({"all"}) public class LinkedHashSetSource { public static void main(String[] args) { LinkedHashSet linkedHashSet = new LinkedHashSet(); linkedHashSet.add(new String("AA")); linkedHashSet.add(456); linkedHashSet.add(456); linkedHashSet.add(new Employee("jake", 28)); linkedHashSet.add(123); linkedHashSet.add("pero"); Iterator iterator = linkedHashSet.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); System.out.println(next); } for (Object o : linkedHashSet) { System.out.println(o); } //1.LinkedHashSet 加入顺序和取出元素/数据的顺序一致 //2.LinkedHashSet 底层维护的是一个LinkedHashMap(是HashMap的子类) //3.LinkedHashSet 底层结构(数组+双向链表) //4.第一次添加元素时,直接将 数组table扩容到16个空间,table类型是HashMap$Node类, // 存放的节点类型不再是Node类型,而是LinkedHashMap$Entry类,并且是HashMap$Node类的子类或者实现类关系 // 子类对象可以存放到父类的数组中(多态数组),否则节点无法存放到table数组 } }
源码运行流程
1.执行构造器
public LinkedHashSet() { super(16, .75f, true); }
HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }
public LinkedHashMap(int initialCapacity, float loadFactor) { super(initialCapacity, loadFactor); accessOrder = false; }
public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; this.threshold = tableSizeFor(initialCapacity); }
/** * Returns a power of two size for the given target capacity. */ static final int tableSizeFor(int cap) { int n = cap - 1; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; }
2执行add()方法,添加元素
public boolean add(E e) { return map.put(e, PRESENT)==null; }
public V put(K key, V value) { return putVal(hash(key), key, value, false, true); }
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; }
final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) { Node<K,V>[] tab; Node<K,V> 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<K,V> 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<K,V>)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) { // existing mapping for key V oldValue = e.value; if (!onlyIfAbsent || oldValue == null) e.value = value; afterNodeAccess(e); return oldValue; } } ++modCount; if (++size > threshold) resize(); afterNodeInsertion(evict); return null; }
final Node<K,V>[] resize() { Node<K,V>[] oldTab = table; int oldCap = (oldTab == null) ? 0 : oldTab.length; int oldThr = threshold; int newCap, newThr = 0; if (oldCap > 0) { if (oldCap >= MAXIMUM_CAPACITY) { threshold = Integer.MAX_VALUE; return oldTab; } else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY && oldCap >= DEFAULT_INITIAL_CAPACITY) newThr = oldThr << 1; // double threshold } else if (oldThr > 0) // initial capacity was placed in threshold newCap = oldThr; else { // zero initial threshold signifies using defaults newCap = DEFAULT_INITIAL_CAPACITY; newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); } if (newThr == 0) { float ft = (float)newCap * loadFactor; newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ? (int)ft : Integer.MAX_VALUE); } threshold = newThr; @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap]; table = newTab; if (oldTab != null) { for (int j = 0; j < oldCap; ++j) { Node<K,V> e; if ((e = oldTab[j]) != null) { oldTab[j] = null; if (e.next == null) newTab[e.hash & (newCap - 1)] = e; else if (e instanceof TreeNode) ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); else { // preserve order Node<K,V> loHead = null, loTail = null; Node<K,V> hiHead = null, hiTail = null; Node<K,V> next; do { next = e.next; if ((e.hash & oldCap) == 0) { if (loTail == null) loHead = e; else loTail.next = e; loTail = e; } else { if (hiTail == null) hiHead = e; else hiTail.next = e; hiTail = e; } } while ((e = next) != null); if (loTail != null) { loTail.next = null; newTab[j] = loHead; } if (hiTail != null) { hiTail.next = null; newTab[j + oldCap] = hiHead; } } } } } return newTab; }
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) { LinkedHashMap.Entry<K,V> p = new LinkedHashMap.Entry<K,V>(hash, key, value, e); linkNodeLast(p); return p; }
static class Entry<K,V> extends HashMap.Node<K,V> { //该内部类起着作为生成节点的作用,可以生成双向链表 //after指向当前节点的下一个节点 //before指向当前节点的上一个节点 Entry<K,V> before, after; Entry(int hash, K key, V value, Node<K,V> next) { super(hash, key, value, next); } }
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) { LinkedHashMap.Entry<K,V> last = tail; tail = p; if (last == null) head = p; else { p.before = last; last.after = p; } }
练习代码
package com.pero.set_; import java.util.LinkedHashSet; import java.util.Objects; /** * Car类(属性:name ,price)如果name和price都一样, * 则认为是相同元素,不能添加到LinkedHashSet中 * * @author Pero * @version 1.0 */ @SuppressWarnings({"all"}) public class LinkedHashSetExercise { public static void main(String[] args) { LinkedHashSet linkedHashSet = new LinkedHashSet(); linkedHashSet.add(new Car("保时捷", 1200000)); linkedHashSet.add(new Car("奥迪", 600000)); linkedHashSet.add(new Car("宝马", 800000)); linkedHashSet.add(new Car("奔驰", 3000000)); linkedHashSet.add(new Car("法拉利", 9000000)); linkedHashSet.add(new Car("保时捷", 1200000)); for (Object o :linkedHashSet) { System.out.println(o); } } } class Car { private String name; private double price; public Car(String name, double price) { this.name = name; this.price = price; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Car car = (Car) o; return Double.compare(car.price, price) == 0 && Objects.equals(name, car.name); } @Override public int hashCode() { return Objects.hash(name, price); } @Override public String toString() { return "Car{" + name + price + '}'; } }
到此这篇关于Java集合之LinkedHashSet类详解的文章就介绍到这了,更多相关Java的LinkedHashSet类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!