ListIterator.next () returns null

my question is really, very simple, but everything that I find on the Internet tells me that I am doing it right, but I obviously misunderstood something.

I have a simple, simple Java ListIterator that after a while has-hasNext () - loop returns null for next (). Here is 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, a loop should not be entered if there is no next () object - therefore I check the use of hasNext (). What did I misunderstand, and what is the right way?

+4
source share
3 answers

The list has the following element, and this next element is null. For instance:

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

3 . - .

, , , , NullPointerExceptions.

+10

ListIterator , next():

: NoSuchElementException -

, hasNext() . , , currentUser.getRoles() null. [ ] :

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

, . roleObject .

():

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

All Articles