简体   繁体   中英

NullPointerException on iterating through empty container in java

public void clearTrash()
{
    for (Email i1 : trash.getEmails()) trash.removeEmail(trash.getEmails().indexOf(i1));
}

I thought this would simply return if trash.getEmails() is empty since there is nothing to iterate over, but upon debugging with empty folder it throws NullPointerException. Why doesn't that work?

I'm not sure what is logic behind this foreach loop, but I'd recommend you use Iterator to remove items while iterating, ie:

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

As for your NPE, probably trash or maybe trash.getEmails() is null. Check for nulls!

Your trash var is null or the list trash.getEmails() is null

So when you use it, its like

for(Email i1 : null)

Try to get used to evaluate your list before use it:

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

Also, as a side note, it would be better in performance to create a new list instead of removing all his elements.

//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>); 

Always incorporate Defensive programming into your code.

Wherever you see an object ,think what to do if it is null and what if it is not null.

like below,you can implement.

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

check if trash is null.

Use org.apache.commons.collections.CollectionUtils

 if(CollectionUtils.isNotEmpty(trash.getEmails()){

    //Your logic.
 }

isNotEmpty() will check for null as well as empty List.

Please refer to the following thread for a better understanding: How does a for each loop guard against an empty list?

In your case the collection trash is null . So when you dereference trash you get a null pointer exception. So it is not the empty container which gives you the null pointer exception but rather the dereferencing of trash(null object) which results in null pointer exception.

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