< !– more –>
HashSet存储元素的原理:
往hashSet添加元素的时候,首先会调用元素的 hashCode 方法得到元素的哈希码值,然后把哈希码值经过运算算出该元素存在哈希表中的位置。有两种情况:

  • 情况1:如果算出的位置目前还没有存在任何的元素,那么该元素可以直接添加到哈希表中。

  • 情况2: 如果算出的位置目前已经存在其他的元素,那么还会调用元素的 equals 方法再与这个位置上的元素比较一次。
    如果 equals 方法返回的是true,那么该元素被视为重复元素,不允许添加。如果equals方法返回的是false,那么该元素也可以被添加。

先看个最简单的构造方法

* 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<>();
}

很明显,HashSet底层是Hashmap存储的。借大神的话

HashSet 就是HashMap的马甲 —–someone

再看看add方法

// Dummy value to associate with an Object in the backing Map
 private transient HashMap<E,Object> map;
 private static final Object PRESENT = new Object();
/**
     * 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&nbsp;?&nbsp;e2==null&nbsp;:&nbsp;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;
    }

add方法的参数:

  • map:map是一个HashMap的实例
  • e:我们要存储的值,是HashMap的key
  • PRESENT:固定值( Object PRESENT = new Object(); ),空的obj对象

Set偷偷的用了HashMap的 put 方法,然而HashMap并没有去重的功能呀,那么Set是如何做到去重的呢?

从add方法中可以看到,E是我们要存储的值,而到了HashMap里面却变成了Key,PRESENT就是个空对象。

在HashMap中Key的HashCode是决定底层数组的下标,进一步使用 equals 进行遍历对象链表中的Key进而覆盖原来的Value。

那么对于HashSet,如果 e 已经存在(先HashCode相同定位到链表,然后equals比较定位到具体的Node),那么覆盖oldValue(value其实就是个傀儡,没啥用),Key不变;如果不存在,就添加一个新的节点(即加了一个新的Key)。

HashMap的返回值是oldValue,oldValue==null说明节点之前不存在;反之说明节点存在,虽然返回false但实际上还是对底层数据进行了改变(即旧的空对象变成了新的空对象)。

总而言之,HashSet确定相同的方式其实就是HashCode相同(才能找到同一链表),然后equals的返回值(才能比较具体节点进行覆盖)。

重点看key(敲黑板)

HashMap中的put方法

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
   /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

这里边有两个看点:

  • HashMap中key存储是hash后的值,对于String类型的相同值的hash值是一致的(其他接触类型类似,自定义对象类型需要重写hashcode方法与equel方法)。换句话说相同的值在hashMap中的存储位置是一样的。
  • 基于上一点来看看怎么存储重复值的。如下代码对于hashMap中已经存在的key,key不变,新value覆盖就value。对于HashSet而言新旧value都是PRESENT对象,所以set在存储的时候就不会重复。
if (e != null) { // existing mapping for key
    V oldValue = e.value;
    if (!onlyIfAbsent || oldValue == null)
        e.value = value;
        afterNodeAccess(e);
    return oldValue;
}

所以hashset中存储的值输出的顺序和存储的先后顺序不一致,这是因为hashset是按照值的hash顺序进行输出。


YOLO