本文將就JDK1.8的HashSet源碼逐行講解與解釋。由於其內部主要運用了HashMap的實現,涉及到這部分的,可以參考https://blog.csdn.net/u010867670/article/details/87623022 查看HashMap的實現講解。
首先,HashSet<E>接口我們直接看代碼
public class HashMap<K,V> extends AbstractMap<K,V>
implements Map<K,V>, Cloneable, Serializable {
private static final long serialVersionUID = 362498820763181265L;
其中基礎了一個抽象類,實現了3個基本的接口,特別是Set<E>接口,其中transient關鍵字表示 該類的對象在序列化的過程中該屬性不參與序列化,也就是這個字段的生命週期僅存在於調用者的內存中。
{
//序列化ID
static final long serialVersionUID = -5024744406713321676L;
//HashMap,實現HashSet的核心
private transient HashMap<E,Object> map;
//虛擬值,用來關聯備份映射表,作用下文會有涉及
// Dummy value to associate with an Object in the backing Map
private static final Object PRESENT = new Object();
接下來就是一些構造函數。
構造函數
/*
*
* Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
* default initial capacity (16) and load factor (0.75).
*/
HashSet的內部實現就是一個HashMap
public HashSet() {
map = new HashMap<>();
}
/**
* 入參爲集合的構造函數,類型爲E的子類
*/
public HashSet(Collection<? extends E> c) {
//創建一個新的HashMap,大小爲16與7/3*c中大的那個,然後將c全體放入map中
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);
}
/**
* Constructs a new, empty linked hash set. (This package private
* constructor is only used by LinkedHashSet.) The backing
* HashMap instance is a LinkedHashMap with the specified initial
* capacity and the specified load factor.
用LinkedHashMap實現的構造函數,dummy只是一個標識符
*/
HashSet(int initialCapacity, float loadFactor, boolean dummy) {
map = new LinkedHashMap<>(initialCapacity, loadFactor);
}
接下來是一些基礎的方法
/**
* Returns an iterator over the elements in this set. The elements
* are returned in no particular order.
* 返回一個hashmap的鍵集的迭代器(Set接口中的迭代器)
*/
public Iterator<E> iterator() {
return map.keySet().iterator();
}
/**
* Returns the number of elements in this set (its cardinality).
* 返回set中的元素個數,其實就是返回實現中hashmap的size()方法。
*/
public int size() {
return map.size();
}
/**
* Returns <tt>true</tt> if this set contains no elements.
* 判斷HashSet是否爲空
*/
public boolean isEmpty() {
return map.isEmpty();
}
/**
* 返回是否包含某個指定的Object類型的對象,內部實現爲HashMap的containsKey方法
*/
public boolean contains(Object o) {
return map.containsKey(o);
}
/**
* 調用hashmap的put方法,向set中的hashmap對象map添加一個指定的鍵值對,key爲入參e,value爲final類型的對象PRESENT
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
/**
* 通過調用hashmap的remove方法,刪除一個指定的元素,此處通過用返回值是否等於final的PRESENT判斷刪除是否成功
*/
public boolean remove(Object o) {
return map.remove(o)==PRESENT;
}
/**
* 調用hasnmap的clear方法,請出當前HashSet中的所有元素。
*/
public void clear() {
map.clear();
}
然後是HashSet的clone方法,注意這裏是淺拷貝。
/**
* HashSet的clone方法,淺拷貝(只拷貝引用,並未創建新的獨立複製)。
*
*/
@SuppressWarnings("unchecked")
public Object clone() {
try {
HashSet<E> newSet = (HashSet<E>) super.clone();
newSet.map = (HashMap<E, Object>) map.clone();
return newSet;
} catch (CloneNotSupportedException e) {
throw new InternalError(e);
}
}
/**
* Save the state of this <tt>HashSet</tt> instance to a stream (that is,
* serialize it).
*HashSet的持久化方法,內部爲ObjectOutputStream的方法調用
*/
private void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException {
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out HashMap capacity and load factor
s.writeInt(map.capacity());
s.writeFloat(map.loadFactor());
// Write out size
s.writeInt(map.size());
// Write out all elements in the proper order.
for (E e : map.keySet())
s.writeObject(e);
}
/**
* HashSet的讀方法
*/
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
// Read in any hidden serialization magic
s.defaultReadObject();
// Read capacity and verify non-negative.
int capacity = s.readInt();
if (capacity < 0) { //基礎判斷是否容量小於0
throw new InvalidObjectException("Illegal capacity: " +
capacity);
}
// Read load factor and verify positive and non NaN.
float loadFactor = s.readFloat();
if (loadFactor <= 0 || Float.isNaN(loadFactor)) {
throw new InvalidObjectException("Illegal load factor: " +
loadFactor);
}
// Read size and verify non-negative.基礎校驗當前元素數量大於等於0
int size = s.readInt();
if (size < 0) {
throw new InvalidObjectException("Illegal size: " +
size);
}
// Set the capacity according to the size and load factor ensuring that
// the HashMap is at least 25% full but clamping to maximum capacity.
capacity = (int) Math.min(size * Math.min(1 / loadFactor, 4.0f),
HashMap.MAXIMUM_CAPACITY);
// Constructing the backing map will lazily create an array when the first element is
// added, so check it before construction. Call HashMap.tableSizeFor to compute the
// actual allocation size. Check Map.Entry[].class since it's the nearest public type to
// what is actually created.
SharedSecrets.getJavaOISAccess()
.checkArray(s, Map.Entry[].class, HashMap.tableSizeFor(capacity));
// Create backing HashMap
map = (((HashSet<?>)this) instanceof LinkedHashSet ?
new LinkedHashMap<E,Object>(capacity, loadFactor) :
new HashMap<E,Object>(capacity, loadFactor));
// Read in all elements in the proper order. 逐個讀取然後放入到實現map對象中
for (int i=0; i<size; i++) {
@SuppressWarnings("unchecked")
E e = (E) s.readObject();
map.put(e, PRESENT);
}
}
/**
* 創建一個HashMap的分割迭代器用於迭代HashSet,KeySpliterator後面的幾個參數分別爲對象,當前節點,當前遍歷的通的索引,遍歷的個數,變化量。HashMapSpliterator(HashMap<K,V> m, int origin,
int fence, int est,
int expectedModCount)
*/
public Spliterator<E> spliterator() {
return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0);
}
到這裏,HashSet的源碼就結束了,相對來說其源碼實現還是比較簡單的,主要是通過HashMap來實現了一個Set的功能,其中的方法調用也都是HashMap的方法。所以如果有不理解的,還請翻閱HashMap源碼解讀:https://blog.csdn.net/u010867670/article/details/87623022