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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With