2012-04-27 41 views
0
public void clearTrash() 
{ 
    for (Email i1 : trash.getEmails()) trash.removeEmail(trash.getEmails().indexOf(i1)); 
} 

迭代我认为这将只是返回,如果trash.getEmails()是空的,因为没有什么可迭代,但在与空文件夹调试它抛出NullPointerException异常。为什么这不起作用?的NullPointerException通过空容器中的Java

+1

你检查垃圾对象为空吗? – sgowd 2012-04-27 04:40:53

+1

你能否给出详细的堆栈跟踪?另外,如果你可以给removeEmail()的源码,那会很有用。 – Garbage 2012-04-27 04:42:44

回答

0

trash var为null或列表trash.getEmails()为空

所以当你使用它,习惯它像

for(Email i1 : null) 

尝试评估您的列表之前使用它:

if (trash != null) { 
    //some logic here... 
    if (trash.getEmails() != null) { 
     for(Email i1 : null) { 
      //your code... 
     } 
    } 
} 

另外,作为一个方面说明,创建一个新列表而不是删除所有元素会更好。

//deleting the items in the List<Email> 
//maybe the collection is not List, just a supposition, still the idea is the same 
trash.setEmails(new List<Email>); 
2

我不知道这背后foreach循环逻辑,但我建议你使用Iterator删除在迭代的项目,即:

Iterator<Email> it = trash.iterator(); 
while (it.hasNext()) { 
    // some logic .... 
    it.remove(); 
} 

至于你的NPE,大概trash或者trash.getEmails()为空。检查空值!

0

总是将Defensive programming合并到您的代码中。

无论你在哪里看到一个对象,都应该考虑如果它为null,如果它不为null,该怎么办。

就像下面那样,你可以实现。

if(object==null){ 
    //doSomething() 
    }else{ 
//doSomethingElse() 
    } 

检查垃圾箱是否为空。

+1

而不是其他的,如果你可以有一个其他的本身。 – 2012-04-27 05:00:14

+0

感谢我们的评论编辑我的帖子 – 2012-04-27 05:03:29

0

请参考以下螺纹的更好的理解:How does a for each loop guard against an empty list?

在你的情况下,收集垃圾是。所以当你解引用垃圾时,你会得到一个空指针异常。所以它不是空的容器,它给你空指针异常,而是垃圾(空对象)的解引用导致空指针异常。