首頁  >  文章  >  Java  >  Core Java簡單介紹HashSet

Core Java簡單介紹HashSet

黄舟
黄舟原創
2017-09-19 11:43:191799瀏覽

下面小編就為大家帶來一篇Core Java 簡單談談HashSet(推薦)。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧

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

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 ? e2==null : 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的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn