Java集合之LinkedHashSet類詳解
LinkedHashSet類
LinkedHashSet是HashSet的子類;
LinkedHashSet底層是一個LinkedHashMap,底層維護了一個數(shù)組+雙向鏈表;
LinkedHashSet根據(jù)元素的hashCode值來決定元素的存儲位置,同時使用鏈表維護元素的次序,這使得元素看起來是以插入順序保存的;
- 在LinkedHashSet中維護了一個hash表和雙向鏈表(LinkedHshSet有head和tail);
- 每一個節(jié)點有pre和next屬性,這樣可以形成雙向鏈表;
- 在添加一個元素時,先求hash值,再求索引,確定該元素在hashtable的位置,然后將添加的元素加入到雙向鏈表(如果已經(jīng)存儲過相同元素,則不再添加,原則和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 加入順序和取出元素/數(shù)據(jù)的順序一致
//2.LinkedHashSet 底層維護的是一個LinkedHashMap(是HashMap的子類)
//3.LinkedHashSet 底層結構(數(shù)組+雙向鏈表)
//4.第一次添加元素時,直接將 數(shù)組table擴容到16個空間,table類型是HashMap$Node類,
// 存放的節(jié)點類型不再是Node類型,而是LinkedHashMap$Entry類,并且是HashMap$Node類的子類或者實現(xiàn)類關系
// 子類對象可以存放到父類的數(shù)組中(多態(tài)數(shù)組),否則節(jié)點無法存放到table數(shù)組
}
}源碼運行流程
1.執(zhí)行構造器
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執(zhí)行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> {
//該內(nèi)部類起著作為生成節(jié)點的作用,可以生成雙向鏈表
//after指向當前節(jié)點的下一個節(jié)點
//before指向當前節(jié)點的上一個節(jié)點
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類內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法
這篇文章主要介紹了SpringBoot使用Mybatis&Mybatis-plus文件映射配置方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-05-05
Java 中的CharArrayReader 介紹_動力節(jié)點Java學院整理
CharArrayReader 是字符數(shù)組輸入流。它和ByteArrayInputStream類似,只不過ByteArrayInputStream是字節(jié)數(shù)組輸入流,而CharArray是字符數(shù)組輸入流。CharArrayReader 是用于讀取字符數(shù)組,它繼承于Reader2017-05-05
Java使用Lambda表達式查找list集合中是否包含某值問題
Java使用Lambda表達式查找list集合中是否包含某值的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06

