溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Core Java 簡單談談HashSet(推薦)

發布時間:2020-08-30 17:56:44 來源:腳本之家 閱讀:178 作者:jingxian 欄目:編程語言

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

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(推薦)就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女