HashSet源码+ 示例解读

如果你还在背HashSet的特性时, 我建议你放下,然后去看HashSet的源代码;

如果你在看HashSet源代码之前还没看HashMap的源代码, 我建议你先去研究HashMap源代码。

===========================================================

如果你看过源代码,你就知道:  HashSet内部维护这一个 HashMap对象,然后,所有的操作都围绕着这个HashMap来。

另外一个真相:HashSet 集合的 元素,其实是存储在HashMap 的Key键上的。 

这个真相也解释了:为啥HashSet 集合,是不能含有重复的元素的。。。 因为 key 不能重复啊。 so ...


1、下面给出部分重要的源代码:

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable    // 继承和实现的
{
    static final long serialVersionUID = -5024744406713321676L;

    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).    // 无参构造器,并创建HashMap
     */
    public HashSet() {
        map = new HashMap<>();
    }
 public Iterator<E> iterator() {                    // 迭代器, 
        return map.keySet().iterator();
    }

    /**
     * Returns the number of elements in this set (its cardinality).
     *
     * @return the number of elements in this set (its cardinality)
     */
    public int size() {
        return map.size();
    }

    /**
     * Returns <tt>true</tt> if this set contains no elements.
     *
     * @return <tt>true</tt> if this set contains no elements
     */
    public boolean isEmpty() {
        return map.isEmpty();
    }

    /**
     * Returns <tt>true</tt> if this set contains the specified element.
     * More formally, returns <tt>true</tt> if and only if this set
     * contains an element <tt>e</tt> such that
     * <tt>(o==null ? e==null : o.equals(e))</tt>.
     *
     * @param o element whose presence in this set is to be tested
     * @return <tt>true</tt> if this set contains the specified element
     */
    public boolean contains(Object o) {
        return map.containsKey(o);
    }

    /**
     * Adds the specified element to this set if it is not already present.
     * More formally, adds the specified element <tt>e</tt> to this set if
     * this set contains no element <tt>e2</tt> such that
     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.
     * If this set already contains the element, the call leaves the set
     * unchanged and returns <tt>false</tt>.
     *
     * @param e element to be added to this set
     * @return <tt>true</tt> if this set did not already contain the specified
     * element
     */
    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

2、下面是我的测试代码:

public class HashSetDemo {

    public static void main(String[] args) {

        HashSet hashSet = new HashSet();
       for(int i=0;i<10;i++){
           hashSet.add(i);
       }

       hashSet.add(3);     // 方法1,已经存在的元素添加不进去
        System.out.println(hashSet);

        /**
         * 通过add(E e) 的源码就可以推测:为什么HashSet 集合里面的元素不能重复了。
         *
         * hashSet 里面维护着一个HashMap,  并且, hashset 的元素本质是 在HashMap的Key值。
         *
         * 因为key 不能重复,所以,hashSet 的值 也是不能重复的。
         */

        hashSet.add(null);  // 貌似可以添加 null 。
        System.out.println("添加了null:"+ hashSet);

        /*------------------------------------------------------------------*/

        /*迭代器的实现,其实是 HashMap key的迭代*/
         Iterator it =  hashSet.iterator();  //方法2,迭代
         while(it.hasNext()){
             System.out.println(it.next());
         }

         boolean b=  hashSet.contains(null);   // 方法3,,判断是否含有此元素
        System.out.println("判断是否有此元素:"+b);


        HashSet ob = (HashSet)hashSet.clone();  // 方法4: 浅拷贝
        System.out.println(ob);

        /*测试, 当克隆体改变了, 原本的集合是否会改变*/

        ob.remove(null);                    // 视乎, 拷贝的集合修改并不影响本尊
        System.out.println("克隆的集合:"+ob);
        System.out.println("原本的集合:"+hashSet);


        /*测试2:, 克隆修改,对其他克隆的影响*/
        HashSet ob1 = (HashSet)hashSet.clone();
        HashSet ob2 = (HashSet)hashSet.clone();
        ob.remove(1);
        hashSet.remove(2);                  // 奇怪,  不管是克隆的集合还是本尊, 修改后都对其他的克隆集合没有影响?
        System.out.println("克隆的集合:"+ob);
        System.out.println("克隆1的集合:"+ob1);
        System.out.println("克隆2的集合:"+ob2);
        System.out.println("集合:"+hashSet);

    }


}


===============================================================

结束。。。 

**内容比较简单, 后面继续补充**






猜你喜欢

转载自blog.csdn.net/qq_41694349/article/details/79456155