[英]Null pointer with iterator.next
下面是java中的代碼片段。
Collection contextPages = (Collection) getContextPages();
Iterator contextPageIter = contextPages.iterator();
while (contextPageIter.hasNext()) {
Page contextPage = (Page) contextPageIter.next();
String result = contextPage.getResult(); // <-- Null pointer exception here
// Other stuff which this API does.
}
這段代碼已經投入生產一段時間了。 但是出於某種原因,我們在String result = contextPage.getResult();
處遇到了一個空指針String result = contextPage.getResult();
.
所以看起來即使我們檢查了hasNext()
, next()
方法還是返回null
。
一種可能性是集合本身有一個null
,但是這個代碼是否有可能在多線程環境中產生一個空指針?
一些集合允許你添加一個空值,所以 iter.next 會返回它,當你使用它時 -> NPE
展示
@Test
public void testNull() {
Collection<Object> c = new ArrayList<>();
c.add(null);
Iterator<Object> iterator = c.iterator();
Assert.assertTrue(iterator.hasNext());
Object o = iterator.next();
Assert.assertNull(o);
}
因此,在使用Iterator#next()
的結果之前,請檢查您是否沒有向集合添加null
引用或檢查是否為null
Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
result = contextPage.getResult();
}
單線程和多線程應用程序之間應該沒有區別,只要確保不要添加null
。
最好在使用 Iterator.next() 的結果之前檢查 null
嘗試這個 -
Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
result = contextPage.getResult();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.