Potential null pointer access

天涯浪子 提交于 2019-12-06 03:21:54

I think it is somehow answered by Ed Merks within this forum post:

http://www.eclipse.org/forums/index.php/t/278687/

From what I understand, Eclipse raises the warning once you assume a variable to potentially be null in the preceding code. You can do so by just check against null (either equal or not equal) - but you do have to have it separated somewhere as a variable, not simply as an if's solely expression.

This is probably not the cause of the warning but here you can have a null pointer.

for (Item item : items.getItems())
{
    // potential null pointer access: the variable itemName might be null at this location
    if (itemName.equals(item.getName()))
    {
        return item;
    }
}

You iterate over objects, but the object returned can be null. So item.getName() can cause a null pointer exception.

Exmaple

 List<String> l = new ArrayList<String>();
 l.add("test");
 l.add(null);
 l.add("another string");

 if(l == null)   // <-- this is similar to the above check
    return;

 for(String s : l)
 {
     s.charAt(0);   //  <-- null pointer access on second item.
 }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!