`
wangqisen
  • 浏览: 47085 次
文章分类
社区版块
存档分类
最新评论

【jdk源码解析四】java.uti.HashSet源码解析

 
阅读更多

HashSet与ArrayList的最主要区别在于,在HashSet中的元素不会出现重复的。其内部实现机制如下:

为了保证在HashSet中出现重复元素,实际上,HashSet是通过一个内部的HashMap来实现元素唯一性。

 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).
     */
    public HashSet() {
        map = new HashMap<>();
    }

    /**
     * Constructs a new set containing the elements in the specified
     * collection.  The <tt>HashMap</tt> is created with default load factor
     * (0.75) and an initial capacity sufficient to contain the elements in
     * the specified collection.
     *
     * @param c the collection whose elements are to be placed into this set
     * @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);
    }

在上面代码中可以看出,在HashSet初始化时,如果初始化集合为空,则会初始化一个空的HashMap,也就是初始容量为16,初始装载因子为0.75的HashMap。

如果初始化集合不为空,则会初始化一个初始装载因子为0.75的HashMap。



HashSet中的所有的元素都被作为key值,以一个初始化的变量PRESENT作为值来构建它内部的HashMap。


HashSet继承自AbstractSet抽象类和Set接口。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics