54 容器(九)——HashSet

HashSet的特点:

无序,不可重复。

HashSet实现自Set,而Set继承自Collection,在日常使用中,我们都是以Set引用指向HashSet对象的方式。

所以,Set中的方法是我们主要学习的,而Set中的方法与属性,基本都是Collection里的方法与属性。

主要有以下 :

HashSet的底层分析

HashSet的底层是一个HashMap,这个HashMap的key即是Hash的元素,而对应的value为null。

正因为HashSet的底层死HashMap,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<>();
    }  
原文地址:https://www.cnblogs.com/Scorpicat/p/12031246.html