1. 程式人生 > >JDK原始碼解讀 HashSet

JDK原始碼解讀 HashSet

    //繼承了AbstractSet抽象類,實現了Set介面,在HashMap基礎上實現了Set的操作,原始碼比較簡單  
    public class HashSet<E>  extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable  
    {  
        //內部儲存結構,通過HashMap來儲存,Set集合的值作為Map的鍵,Map的值為一個物件,其實值根本不重要  
        private transient HashMap<E,Object> map;  

        //用來填充HashMap的值物件  
private static final Object PRESENT = new Object(); //建立空的Set,Map對應的初始化為:裝載因子為0.75,容量為16 public HashSet() { map = new HashMap<>(); } //新增集合的值 public HashSet(Collection<? extends E> c) { map = new HashMap<>(Math.max((int
) (c.size()/.75f) + 1, 16));//建立Map addAll(c);//新增元素 } //按容量和裝載因子建立 public HashSet(int initialCapacity, float loadFactor) { map = new HashMap<>(initialCapacity, loadFactor); } //裝載因子為0.75 public HashSet(int initialCapacity) { map = new
HashMap<>(initialCapacity); } //內部結構為LinkedHashMap,這個是提供給LinkedHashSet用的,不是給HashSet使用的 HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); } //返回迭代器 public Iterator<E> iterator() { return map.keySet().iterator(); } //返回容量 public int size() { return map.size(); } //判斷是否為空 public boolean isEmpty() { return map.isEmpty(); } //是否包含元素o public boolean contains(Object o) { return map.containsKey(o); } //新增元素 public boolean add(E e) { return map.put(e, PRESENT)==null;//新增元素,鍵為e,值為PRESENT } //刪除元素 public boolean remove(Object o) { return map.remove(o)==PRESENT; } //清除所有元素 public void clear() { map.clear(); } //淺複製 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(); } } }