Core Java 簡單談談HashSet

來源:互聯網
上載者:User

標籤:str   shm   already   nbsp   sso   ini   ansi   leaves   index   

  同學們在看這個問題的時候,我先提出者兩個問題,然後大家帶著問題看這個文章會理解的更好。

  1. HashSet為什麼添加元素時不能添加重複元素?
  2. HashSet是否添加null元素?

  開啟源碼, 我們看到如下代碼,我們看到HashSet也有一個HashMap做為屬性,HashSet()的構造方法就是將這個map執行個體化。如果大家對HashMap還不瞭解話,可以看我的這篇博文。還要注意有一個靜態final的對象PRESENT,這個是幹什麼用的,咱們繼續往下看。

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

  然後我們再開啟其add方法,其就是將元素e放到HashMap中,然後將靜態final對象PRESENT作為value放到裡邊,如果添加成功,那麼HashMap返回null,然後也就是添加成功了,上一篇博文也講到了,咱們再講一次作為複習。如果將element放到HashMap裡邊,首先判斷其hashCode,如果hashCode沒有找到,就根據hashCode計算index放到對應的bucket中,如果hashCode相同的話,那麼再根據key的是否equals作為第二判斷,放到相應的linked list裡邊了。

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

  當然第二個問題同學們是否也想到了,因為hashMap是支援key為null的,所以HashSet也是可以添加key為null的元素的。HashMap用的地方這麼多,大家知道它很重要了吧?!

Core Java 簡單談談HashSet

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.