Java Coder

          HashSet 類分析

            1 package java.util;
            2 
            3 public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable,
            4         java.io.Serializable {
            5     static final long serialVersionUID = -5024744406713321676L;
            6 
            7     // 內部的HashMap對象,不可被串行化。存儲的元素作為key,保證不會重復
            8     private transient HashMap<E, Object> map;
            9 
           10     // Dummy value to associate with an Object in the backing Map
           11     private static final Object PRESENT = new Object();
           12 
           13     /**
           14      * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
           15      * default initial capacity (16) and load factor (0.75).
           16      */
           17     public HashSet() {
           18         map = new HashMap<E, Object>();
           19     }
           20 
           21     /**
           22      * Constructs a new set containing the elements in the specified collection.
           23      * The <tt>HashMap</tt> is created with default load factor (0.75) and an
           24      * initial capacity sufficient to contain the elements in the specified
           25      * collection.
           26      * 
           27      * @param c
           28      *            the collection whose elements are to be placed into this set
           29      * @throws NullPointerException
           30      *             if the specified collection is null
           31      */
           32     public HashSet(Collection<? extends E> c) {
           33         map = new HashMap<E, Object>(Math.max((int) (c.size() / .75f) + 116));
           34         // 對集合c中的每個元素,調用add(e)方法
           35         addAll(c);
           36     }
           37 
           38     /**
           39      * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
           40      * the specified initial capacity and the specified load factor.
           41      * 
           42      * @param initialCapacity
           43      *            the initial capacity of the hash map
           44      * @param loadFactor
           45      *            the load factor of the hash map
           46      * @throws IllegalArgumentException
           47      *             if the initial capacity is less than zero, or if the load
           48      *             factor is nonpositive
           49      */
           50     public HashSet(int initialCapacity, float loadFactor) {
           51         map = new HashMap<E, Object>(initialCapacity, loadFactor);
           52     }
           53 
           54     /**
           55      * Constructs a new, empty set; the backing <tt>HashMap</tt> instance has
           56      * the specified initial capacity and default load factor (0.75).
           57      * 
           58      * @param initialCapacity
           59      *            the initial capacity of the hash table
           60      * @throws IllegalArgumentException
           61      *             if the initial capacity is less than zero
           62      */
           63     public HashSet(int initialCapacity) {
           64         map = new HashMap<E, Object>(initialCapacity);
           65     }
           66 
           67     /**
           68      * Constructs a new, empty linked hash set. (This package private
           69      * constructor is only used by LinkedHashSet.) The backing HashMap instance
           70      * is a LinkedHashMap with the specified initial capacity and the specified
           71      * load factor.
           72      * 
           73      * @param initialCapacity
           74      *            the initial capacity of the hash map
           75      * @param loadFactor
           76      *            the load factor of the hash map
           77      * @param dummy
           78      *            ignored (distinguishes this constructor from other int, float
           79      *            constructor.)
           80      * @throws IllegalArgumentException
           81      *             if the initial capacity is less than zero, or if the load
           82      *             factor is nonpositive
           83      */
           84     HashSet(int initialCapacity, float loadFactor, boolean dummy) {
           85         map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
           86     }
           87 
           88     /**
           89      * Returns an iterator over the elements in this set. The elements are
           90      * returned in no particular order.
           91      * 
           92      * @return an Iterator over the elements in this set
           93      * @see ConcurrentModificationException
           94      */
           95     public Iterator<E> iterator() {
           96         // 依賴HashMap中對iterator()的實現
           97         return map.keySet().iterator();
           98     }
           99 
          100     /**
          101      * Returns the number of elements in this set (its cardinality).
          102      * 
          103      * @return the number of elements in this set (its cardinality)
          104      */
          105     public int size() {
          106         return map.size();
          107     }
          108 
          109     /**
          110      * Returns <tt>true</tt> if this set contains no elements.
          111      * 
          112      * @return <tt>true</tt> if this set contains no elements
          113      */
          114     public boolean isEmpty() {
          115         return map.isEmpty();
          116     }
          117 
          118     /**
          119      * Returns <tt>true</tt> if this set contains the specified element. More
          120      * formally, returns <tt>true</tt> if and only if this set contains an
          121      * element <tt>e</tt> such that
          122      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>.
          123      * 
          124      * @param o
          125      *            element whose presence in this set is to be tested
          126      * @return <tt>true</tt> if this set contains the specified element
          127      */
          128     public boolean contains(Object o) {
          129         return map.containsKey(o);
          130     }
          131 
          132     /**
          133      * Adds the specified element to this set if it is not already present. More
          134      * formally, adds the specified element <tt>e</tt> to this set if this set
          135      * contains no element <tt>e2</tt> such that
          136      * <tt>(e==null&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;e.equals(e2))</tt>. If this
          137      * set already contains the element, the call leaves the set unchanged and
          138      * returns <tt>false</tt>.
          139      * 
          140      * @param e
          141      *            element to be added to this set
          142      * @return <tt>true</tt> if this set did not already contain the specified
          143      *         element
          144      */
          145     public boolean add(E e) {
          146         // map.put(key,value)方法在key之前不存在的時候,返回null
          147         return map.put(e, PRESENT) == null;
          148     }
          149 
          150     /**
          151      * Removes the specified element from this set if it is present. More
          152      * formally, removes an element <tt>e</tt> such that
          153      * <tt>(o==null&nbsp;?&nbsp;e==null&nbsp;:&nbsp;o.equals(e))</tt>, if this
          154      * set contains such an element. Returns <tt>true</tt> if this set contained
          155      * the element (or equivalently, if this set changed as a result of the
          156      * call). (This set will not contain the element once the call returns.)
          157      * 
          158      * @param o
          159      *            object to be removed from this set, if present
          160      * @return <tt>true</tt> if the set contained the specified element
          161      */
          162     public boolean remove(Object o) {
          163         // map.remove(key)方法返回相應的value,或者null
          164         return map.remove(o) == PRESENT;
          165     }
          166 
          167     /**
          168      * Removes all of the elements from this set. The set will be empty after
          169      * this call returns.
          170      */
          171     public void clear() {
          172         map.clear();
          173     }
          174 
          175     /**
          176      * Returns a shallow copy of this <tt>HashSet</tt> instance: the elements
          177      * themselves are not cloned.
          178      * 
          179      * @return a shallow copy of this set
          180      */
          181     public Object clone() {
          182         try {
          183             HashSet<E> newSet = (HashSet<E>super.clone();
          184             newSet.map = (HashMap<E, Object>) map.clone();
          185             return newSet;
          186         } catch (CloneNotSupportedException e) {
          187             throw new InternalError();
          188         }
          189     }
          190 
          191     /**
          192      * Save the state of this <tt>HashSet</tt> instance to a stream (that is,
          193      * serialize it).
          194      * 
          195      * @serialData The capacity of the backing <tt>HashMap</tt> instance (int),
          196      *             and its load factor (float) are emitted, followed by the size
          197      *             of the set (the number of elements it contains) (int),
          198      *             followed by all of its elements (each an Object) in no
          199      *             particular order.
          200      */
          201     private void writeObject(java.io.ObjectOutputStream s)
          202             throws java.io.IOException {
          203         // Write out any hidden serialization magic
          204         s.defaultWriteObject();
          205 
          206         // Write out HashMap capacity and load factor
          207         s.writeInt(map.capacity());
          208         s.writeFloat(map.loadFactor());
          209 
          210         // Write out size
          211         s.writeInt(map.size());
          212 
          213         // Write out all elements in the proper order.
          214         for (Iterator i = map.keySet().iterator(); i.hasNext();)
          215             s.writeObject(i.next());
          216     }
          217 
          218     /**
          219      * Reconstitute the <tt>HashSet</tt> instance from a stream (that is,
          220      * deserialize it).
          221      */
          222     private void readObject(java.io.ObjectInputStream s)
          223             throws java.io.IOException, ClassNotFoundException {
          224         // Read in any hidden serialization magic
          225         s.defaultReadObject();
          226 
          227         // Read in HashMap capacity and load factor and create backing HashMap
          228         int capacity = s.readInt();
          229         float loadFactor = s.readFloat();
          230         // 根據對象類型,創建LinkedHashMap或者HashMap
          231         map = (((HashSet) thisinstanceof LinkedHashSet ? new LinkedHashMap<E, Object>(
          232                 capacity, loadFactor)
          233                 : new HashMap<E, Object>(capacity, loadFactor));
          234 
          235         // Read in size
          236         int size = s.readInt();
          237 
          238         // Read in all elements in the proper order.
          239         for (int i = 0; i < size; i++) {
          240             E e = (E) s.readObject();
          241             map.put(e, PRESENT);
          242         }
          243     }
          244 }
          245 

          小結:
          1. HashSet內部用一個HashMap的keyset保存數據元素。由HashMap的特性——所有的key不會重復,保證了HashSet中的所有元素不會重復。
          2. HashSet的方法很簡單,一般都是直接調用HashMap的實現方法。HashSet甚至沒有實現iterator()方法,也是依賴HashMap的實現。
          3. 串行化的readObject()和writeObject()方法設計思想值得學習。

          posted on 2008-07-19 21:35 fred.li 閱讀(489) 評論(0)  編輯  收藏 所屬分類: java.util 包分析

          主站蜘蛛池模板: 巴林右旗| 托克逊县| 焉耆| 根河市| 上犹县| 定远县| 集贤县| 丹凤县| 维西| 涿鹿县| 诏安县| 岳阳市| 西昌市| 平乐县| 天等县| 清苑县| 肥西县| 广灵县| 景谷| 叙永县| 阜南县| 旅游| 丰顺县| 昌邑市| 阿城市| 天水市| 鄢陵县| 赤峰市| 东方市| 秀山| 厦门市| 安西县| 扎赉特旗| 乐至县| 扶余县| 紫金县| 灵山县| 洱源县| 图片| 湘西| 溧水县|