javalistiteratorjava-collections-api

Why this exception is thrown when I try to use an iterator on this list?


I have a collection of this type:

List<com.liferay.portal.model.Role> ruoli
ruoli = currentUser.getRoles(); 

that contains 3 elements (I see it using the debugger), each Role object have a name field and the 3 objects into the previos list have the following names: Administrator, Power User and User.

So I am trying to use an iterator to iterate on this list and print the values of the name field of these 3 objects contained into the ruoli list, so I do in this way:

Iterator<Role> iteratorUserRoles = ruoli.iterator();

while (iteratorUserRoles.hasNext()) {
    System.out.println(iteratorUserRoles.next().getName());
    iteratorUserRoles.next();
}

The problem is that it don't show

but in the stacktrace I obtain:

**Administrator**
**Power User**
**User**

as I expect but I obtain this message:

**Administrator**
**User**

and then it throws this exception:

2015-01-26 10:20:13,071 [[ACTIVE] ExecuteThread: '1' for queue: 'weblogic.kernel.Default (self-tuning)'] ERROR commons.CommonsLogger.error(38) - Could not execute action java.util.NoSuchElementException

It seems that the exception is thrown when it try to perform this operation:

iteratorUserRoles.next();

Why? What could be the problem? What am I mising? How can I fix this issue and correctly iterate on all the objects into my list?

Tnx


Solution

  • You are advancing the iterator twice in each iteration.

    while (iteratorUserRoles.hasNext()) {
        System.out.println(iteratorUserRoles.next().getName());
        //iteratorUserRoles.next(); remove this
    }
    

    If the iterator has one remaining element and you call iteratorUserRoles.next() twice, you'll get an exception.