源码之HashSet

构造函数

    public HashSet() {
        map = new HashMap<>();
    }

    public HashSet(Collection<? extends E> c) {
        map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
        addAll(c);
    }

    public HashSet(int initialCapacity, float loadFactor) {
        map = new HashMap<>(initialCapacity, loadFactor);
    }

    public HashSet(int initialCapacity) {
        map = new HashMap<>(initialCapacity);
    }

   /**
     * Constructs a new, empty linked hash set.  (This package private
     * constructor is only used by LinkedHashSet.) The backing
     * HashMap instance is a LinkedHashMap with the specified initial
     * capacity and the specified load factor.
     *
     * @param      initialCapacity   the initial capacity of the hash map
     * @param      loadFactor        the load factor of the hash map
     * @param      dummy             ignored (distinguishes this
     *             constructor from other int, float constructor.)
     * @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);
    }

分析:
HashSet底层是HashMap实现的,你看最后一个构造函数就会很奇怪,这dummy的参数干啥的 ,啥也没用。不过这个看说明就知道了,只是为了实现构造函数的重载,跟其他区别开来的(如果不明白有必要看下重载内容)。

add方法

    public boolean add(E e) {
        return map.put(e, PRESENT)==null;
    }

分析:
这就很简单可以知道了,就是将E作为HashMap的key,所有的key都指向PRESENT对象,因为我们都知道,key是不允许重复的,而value可以。

另外这里没有HashMap的那种get方法去获取key的,只能通过迭代器去便利里面的值。

总结:
1.它不是线程安全的
2.它是由HashMap实现的
3.通过map.put(key,PRESENT)方式把所有key指向同一个对象
4.访问只能通过迭代器访问。

猜你喜欢

转载自blog.51cto.com/4837471/2309838