Java8之HashSet理解

簡(jiǎn)介

HashSet實(shí)現(xiàn)了Set接口,它不允許集合中有重復(fù)的值。HashSet是對(duì)HashMap的簡(jiǎn)單包裝,對(duì)HashSet的函數(shù)調(diào)用都會(huì)轉(zhuǎn)換成合適的HashMap方法。

具體實(shí)現(xiàn)

public boolean add(Object o)方法用來(lái)在Set中添加元素

add()方法

 public boolean add(E e) {
        //對(duì)map的封裝,如果map.put(e, PRESENT)==null則返回true
        return map.put(e, PRESENT)==null;
    }

從上面源碼可以看出HashSet的add()方法最終調(diào)用HashMap的put()方法,具體實(shí)現(xiàn)可以看[Java 8之HashMap理解]

HashSet如何確保元素不重復(fù)

前面[Java 8之HashMap理解]中提到

  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

 static final int hash(Object key) {
        int h;
        //key.hashCode():如果我們對(duì)象沒有重寫hashCode方法,那么將使用HashMap自身實(shí)現(xiàn)的hashCode方法
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

//HashMap自身實(shí)現(xiàn)的hashCode方法
 public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

//HashMap自身實(shí)現(xiàn)的equal方法
   public final boolean equals(Object o) {
            if (o == this)
                return true;
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }

所以我們將對(duì)象存儲(chǔ)在HashSet之前,要先確保對(duì)象重寫equals()和hashCode()方法,這樣才能比較對(duì)象的值是否相等,以確保set中沒有儲(chǔ)存相等的對(duì)象。如果我們沒有重寫這兩個(gè)方法,將會(huì)使用這個(gè)方法的默認(rèn)實(shí)現(xiàn)。

上面通過(guò)equals()和hashCode()方法可以確保沒有存儲(chǔ)相等對(duì)象了。
當(dāng)元素值重復(fù)時(shí)則會(huì)立即返回false,如果成功添加的話會(huì)返回true。

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;
                }
            }
          //存在重復(fù)的key了,直接返回oldValue 
            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;
    }

//根據(jù)上面的代碼返回的oldValue,那么說(shuō)明map.put(e, PRESENT)!=null,add()方法返回false
 public boolean add(E e) {
        //對(duì)map的封裝,如果map.put(e, PRESENT)==null則返回true
        return map.put(e, PRESENT)==null;
    }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區(qū)別 13、...
    Miley_MOJIE閱讀 3,896評(píng)論 0 11
  • java筆記第一天 == 和 equals ==比較的比較的是兩個(gè)變量的值是否相等,對(duì)于引用型變量表示的是兩個(gè)變量...
    jmychou閱讀 1,647評(píng)論 0 3
  • 實(shí)際上,HashSet 和 HashMap 之間有很多相似之處,對(duì)于 HashSet 而言,系統(tǒng)采用 Hash 算...
    曹振華閱讀 2,561評(píng)論 1 37
  • 上一篇文章介紹了Set集合的通用知識(shí)。Set集合中包含了三個(gè)比較重要的實(shí)現(xiàn)類:HashSet、TreeSet和En...
    Ruheng閱讀 16,137評(píng)論 3 57
  • Carthage使用心得-讓自己的項(xiàng)目支持Carthage使用Carthage發(fā)布Framework
    xiAo__Ju閱讀 927評(píng)論 0 0

友情鏈接更多精彩內(nèi)容