欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Core Java 簡單談?wù)凥ashSet(推薦)

 更新時(shí)間:2017年09月18日 09:53:09   投稿:jingxian  
下面小編就為大家?guī)硪黄狢ore Java 簡單談?wù)凥ashSet(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

同學(xué)們在看這個(gè)問題的時(shí)候,我先提出者兩個(gè)問題,然后大家?guī)е鴨栴}看這個(gè)文章會(huì)理解的更好。

1、HashSet為什么添加元素時(shí)不能添加重復(fù)元素?

2、HashSet是否添加null元素?

打開源碼, 我們看到如下代碼,我們看到HashSet也有一個(gè)HashMap做為屬性,HashSet()的構(gòu)造方法就是將這個(gè)map實(shí)例化。如果大家對(duì)HashMap還不了解話,可以看我的這篇博文。還要注意有一個(gè)靜態(tài)final的對(duì)象PRESENT,這個(gè)是干什么用的,咱們繼續(xù)往下看。

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中,然后將靜態(tài)final對(duì)象PRESENT作為value放到里邊,如果添加成功,那么HashMap返回null,然后也就是添加成功了,上一篇博文也講到了,咱們再講一次作為復(fù)習(xí)。如果將element放到HashMap里邊,首先判斷其hashCode,如果hashCode沒有找到,就根據(jù)hashCode計(jì)算index放到對(duì)應(yīng)的bucket中,如果hashCode相同的話,那么再根據(jù)key的是否equals作為第二判斷,放到相應(yīng)的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;

當(dāng)然第二個(gè)問題同學(xué)們是否也想到了,因?yàn)閔ashMap是支持key為null的,所以HashSet也是可以添加key為null的元素的。HashMap用的地方這么多,大家知道它很重要了吧?!

以上這篇Core Java 簡單談?wù)凥ashSet(推薦)就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論