[英]how to handle null pointer in iteration with null key
在最近的一次采訪中,我遇到的問題是
當迭代器在哈希映射上進行迭代時遇到null鍵時,如何處理null指針。 假設我的開發人員錯誤地插入了一個空鍵
我的答案是:只需要檢查null!=entry.getKey()
。 他不滿意,並在那之前說過您將如何處理。
我應該如何回答這個問題。 當我回來的時候。
我試過了
public class Main {
public static void main(String[] args) {
Map<String,String> map = new HashMap<String,String>();
map.put(null, "null");
map.put("null",null);
map.put("test", "test");
Iterator<Entry<String, String>> it = map.entrySet().iterator();
while(it.hasNext()){
System.out.println(it.next().getKey());
}
}
}
輸出:
null
test
null
也不例外。 他實際上想問什么。 還是我缺少一些概念? 請指導我
map.remove(null)
從JavaDocs:
返回此映射先前與該鍵相關聯的值;如果該映射不包含該鍵的映射關系,則返回null。
如果此映射允許空值,則返回值null不一定表示該映射不包含該鍵的映射;否則,返回0。 映射也可能將鍵顯式映射為null。
調用返回后,該映射將不包含指定鍵的映射。
在迭代之前調用它,它將刪除顯式的空鍵
我想他要通過這個問題測試的關鍵點是在對象Iterator
上調用next()
方法時發生了什么。
他可能想知道您要迭代地圖時是否按照以下方式進行編程:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
if (null != iter.next().key()) {
System.out.println(iter.next());
}
}
如果您像上面的示例那樣進行編程,則next
方法將被調用兩次,並且您將不會獲得真正要檢查的正確對象。 相反,您應該編寫如下代碼:
Map map = new HashMap();
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
// Key point: define a refreence point to the object returned by the
// method `next()`
Entry entry = iter.next();
if (null != entry.key()) {
System.out.println(entry);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.