Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 401
dexBerlin Avatar asked Dec 06 '22 01:12

dexBerlin


1 Answers

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.

like image 145
JB Nizet Avatar answered Dec 23 '22 11:12

JB Nizet