HashMap的put方法返回值问题
API文檔中的描述:
先看一個(gè)例子
可以看出:put方法的返回值為null或value;
調(diào)用put方法時(shí),如果已經(jīng)存在一個(gè)相同的key, 則返回的是前一個(gè)key對應(yīng)的value,同時(shí)該key的新value覆蓋舊value;
如果是新的一個(gè)key,則返回的是null;
通過hashmap的源碼可以看出:
map中一個(gè)映射不能包含重復(fù)的鍵。每個(gè)鍵最多只能映射一個(gè)值。即相同的key在Map中只會有一個(gè)與之關(guān)聯(lián)的value存在。
put()方法實(shí)現(xiàn):首先使用hash(key)得到key的hashcode(),hashmap根據(jù)獲得的hashcode找到要插入的位置所在的鏈,在這個(gè)鏈里面放的都是hashcode相同的Entry鍵值對,
在找到這個(gè)鏈之后,會通過equals()方法判斷是否已經(jīng)存在要插入的鍵值對,而這個(gè)equals比較的就是key。
添加對應(yīng)的key-value這樣的鍵值對node時(shí),如果原本已經(jīng)存在相同的key,則直接改變對應(yīng)的value,并返回舊的value;如果不存在相同的key,則插入,在插入鏈表時(shí),如果鏈表長度為臨界長度TREEIFY_THRESHOLD,再插入任何元素就要變成紅黑樹。
在hashset中的add方法調(diào)用的就是hashmap的put方法,判斷put方法的返回值是否等于空,來保證hashset的值不重復(fù)。
private transient HashMap<E,Object> map;/*** 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;}總結(jié)
以上是生活随笔為你收集整理的HashMap的put方法返回值问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LINUX下用YUM安装nginx出现N
- 下一篇: mxnet基础到提高(43)-编译安装