简体   繁体   中英

Null pointer with iterator.next

Here below is a code snippet in 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.
}

This code has been in production for a while. But for some reason, we hit a null pointer at String result = contextPage.getResult(); .

So looks like even though we did a check for hasNext() , the next() method is returning null .

One possibility is that the collection itself has a null , but is it possible that this code could yield to a null pointer in a multi-threaded environment?

Some collections allow you to add a null, so iter.next will return it and when you use it -> NPE

To demonstrate

@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);
}

So check that you don't add null references to the collection or check for null before using the result of Iterator#next()

Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
        result = contextPage.getResult();
}

There should be no difference between single- and multi- threaded applications, just make sure you don't add null .

Better to check for null before using the result of Iterator.next()

Try this -

Page contextPage = (Page) contextPageIter.next();
String result = null;
if(contextPage != null) {
        result = contextPage.getResult();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM