dexBerlin
dexBerlin

Reputation: 447

ListIterator.next() returns null

my question is really, really simple, but everything I find online tells me I am doing it the right way - but I obviously misunderstood something.

I have a simple, simple Java ListIterator, which in a while-hasNext()-loop returns a null for next(). Here's the code with my comments on the debug state:

[...]
ListIterator<Role> rolesIterator = currentUser.getRoles().listIterator();
// rolesIterator is now: java.util.ArrayList$ListItr
while( rolesIterator.hasNext() ) {
        Role roleObject = rolesIterator.next(); // extra step for debugging reasons
        String role = roleObject.getName(); // NullPointerException - roleObject is null
[...]

In my thoughts, the loop should not be entered, if there is no next() object - that's why I check using hasNext(). What did I understand wrong, and what is the correct way?

Upvotes: 4

Views: 13742

Answers (3)

Azar
Azar

Reputation: 1106

ListIterator documentation states that next():

Throws: NoSuchElementException - if the iteration has no next element

Furthermore, you do the appropriate hasNext() check as the loop condition. So the obvious conclusion is that currentUser.getRoles() contains null elements. To fix [this part of] your code:

while( rolesIterator.hasNext() ) {
    Role roleObject = rolesIterator.next();
    if(roleObject != null)
    {
        String role = roleObject.getName();
        [...]
    }

Upvotes: 1

Jama Djafarov
Jama Djafarov

Reputation: 358

I believe list can contain null values. so the roleObject can be null.

I prefer the for loop approach (cleaner):

for (Role roleObject : currentUser.getRoles()) {
...
}

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691755

There is a next element in the list, and this next element happens to be null. For example:

List<String> list = new ArrayList<>();
list.add("foo");
list.add(null);
list.add("bar");

The above list has 3 elements. The second one is null.

Fix the code that populates the list and make sure it doesn't add any null Role in the list, or check for null inside the loop to avoid NullPointerExceptions.

Upvotes: 15

Related Questions