HashSet

HashSet

HashSet内部使用了HashMap来保存元素。

public class HashSet<E>
    extends AbstractSet<E>
    implements Set<E>, Cloneable, java.io.Serializable

从上面看出 HashSet 继承了抽象类AbstractSet。AbstractSet类里面实现了equals,
hashCode, removeAll这几个方法。

而从构造函数可以发现内部使用了HashMap。

    /**
     * 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

原文地址:https://www.cnblogs.com/SpeakSoftlyLove/p/5570260.html