JDK原始碼分析(4)HashSet
阿新 • • 發佈:2018-12-20
JDK版本
HashSet簡介
HashSet特點
- 非執行緒安全
- 允許null值
- 新增值得時候會先獲取物件的hashCode方法,如果hashCode 方法返回的值一致,則再呼叫equals方法判斷是否一致,如果不一致才add元素。
注意: 對於HashSet中儲存的物件,請注意正確重寫其equals和hashCode方法,以保證放入的物件的唯一性。
HashSet原始碼
public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable { static final long serialVersionUID = -5024744406713321676L; //底層使用HashMap來儲存HashSet中所有元素。 private transient HashMap<E,Object> map; //定義一個虛擬的Object物件作為HashMap的value,將此物件定義為static final。 private static final Object PRESENT = new Object(); /** * 預設的無參構造器,構造一個空的HashSet。 * * 實際底層會初始化一個空的HashMap,並使用預設初始容量為16和載入因子0.75。 */ public HashSet() { map = new HashMap<>(); } /** * 構造一個包含指定collection中的元素的新set。 * * 實際底層使用預設的載入因子0.75和足以包含指定 * collection中所有元素的初始容量來建立一個HashMap。 * @param c 其中的元素將存放在此set中的collection。 * * @throws NullPointerException if the specified collection is null */ public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16)); addAll(c); } /** * 以指定的initialCapacity和loadFactor構造一個空的HashSet。 * * 實際底層以相應的引數構造一個空的HashMap。 * @param initialCapacity 初始容量。 * @param loadFactor 載入因子。 * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<>(initialCapacity, loadFactor); } /** * 以指定的initialCapacity構造一個空的HashSet。 * * 實際底層以相應的引數及載入因子loadFactor為0.75構造一個空的HashMap。 * @param initialCapacity 初始容量。 * @throws IllegalArgumentException if the initial capacity is less * than zero */ public HashSet(int initialCapacity) { map = new HashMap<>(initialCapacity); } /** * 以指定的initialCapacity和loadFactor構造一個新的空連結雜湊集合。 * 此建構函式為包訪問許可權,不對外公開,實際只是是對LinkedHashSet的支援。 * * 實際底層會以指定的引數構造一個空LinkedHashMap例項來實現。 * @param initialCapacity 初始容量。 * @param loadFactor 載入因子。 * @param dummy 標記。! * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); } /** * 返回對此set中元素進行迭代的迭代器。返回元素的順序並不是特定的。 * * 底層實際呼叫底層HashMap的keySet來返回所有的key。 * 可見HashSet中的元素,只是存放在了底層HashMap的key上, * value使用一個static final的Object物件標識。 * @return 對此set中元素進行迭代的Iterator。 * @see ConcurrentModificationException */ public Iterator<E> iterator() { return map.keySet().iterator(); } /** * 返回此set中的元素的數量(set的容量)。 * * 底層實際呼叫HashMap的size()方法返回Entry的數量,就得到該Set中元素的個數。 * @return 此set中的元素的數量(set的容量)。 */ public int size() { return map.size(); } /** * 如果此set不包含任何元素,則返回true。 * * 底層實際呼叫HashMap的isEmpty()判斷該HashSet是否為空。 * @return 如果此set不包含任何元素,則返回true。 */ public boolean isEmpty() { return map.isEmpty(); } /** * 如果此set包含指定元素,則返回true。 * 更確切地講,當且僅當此set包含一個滿足(o==null ? e==null : o.equals(e)) * 的e元素時,返回true。 * * 底層實際呼叫HashMap的containsKey判斷是否包含指定key。 * @param o 在此set中的存在已得到測試的元素。 * @return 如果此set包含指定元素,則返回true。 */ public boolean contains(Object o) { return map.containsKey(o); } /** * 如果此set中尚未包含指定元素,則新增指定元素。 * 更確切地講,如果此 set 沒有包含滿足(e==null ? e2==null : e.equals(e2)) * 的元素e2,則向此set 新增指定的元素e。 * 如果此set已包含該元素,則該呼叫不更改set並返回false。 * * 底層實際將將該元素作為key放入HashMap。 * 由於HashMap的put()方法新增key-value對時,當新放入HashMap的Entry中key * 與集合中原有Entry的key相同(hashCode()返回值相等,通過equals比較也返回true), * 新新增的Entry的value會將覆蓋原來Entry的value,但key不會有任何改變, * 因此如果向HashSet中新增一個已經存在的元素時,新新增的集合元素將不會被放入HashMap中, * 原來的元素也不會有任何改變,這也就滿足了Set中元素不重複的特性。 * @param e 將新增到此set中的元素。 * @return 如果此set尚未包含指定元素,則返回true。 */ public boolean add(E e) { return map.put(e, PRESENT)==null; } /** * 如果指定元素存在於此set中,則將其移除。 * 更確切地講,如果此set包含一個滿足(o==null ? e==null : o.equals(e))的元素e, * 則將其移除。如果此set已包含該元素,則返回true * (或者:如果此set因呼叫而發生更改,則返回true)。(一旦呼叫返回,則此set不再包含該元素)。 * * 底層實際呼叫HashMap的remove方法刪除指定Entry。 * @param o 如果存在於此set中則需要將其移除的物件。 * @return 如果set包含指定元素,則返回true。 */ public boolean remove(Object o) { return map.remove(o)==PRESENT; } /** * 從此set中移除所有元素。此呼叫返回後,該set將為空。 * * 底層實際呼叫HashMap的clear方法清空Entry中所有元素。 */ public void clear() { map.clear(); } /** * 返回此HashSet例項的淺表副本:並沒有複製這些元素本身。 * * 底層實際呼叫HashMap的clone()方法,獲取HashMap的淺表副本,並設定到 HashSet中。 * @return a shallow copy of this set */ @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). * * @serialData The capacity of the backing <tt>HashMap</tt> instance * (int), and its load factor (float) are emitted, followed by * the size of the set (the number of elements it contains) * (int), followed by all of its elements (each an Object) in * no particular order. */ 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); } /** * Reconstitute the <tt>HashSet</tt> instance from a stream (that is, * deserialize it). */ 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) { 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. 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. for (int i=0; i<size; i++) { @SuppressWarnings("unchecked") E e = (E) s.readObject(); map.put(e, PRESENT); } } /** * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em> * and <em>fail-fast</em> {@link Spliterator} over the elements in this * set. * * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and * {@link Spliterator#DISTINCT}. Overriding implementations should document * the reporting of additional characteristic values. * * @return a {@code Spliterator} over the elements in this set * @since 1.8 */ public Spliterator<E> spliterator() { return new HashMap.KeySpliterator<E,Object>(map, 0, -1, 0, 0); } }