1

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

3 Answers 3

5

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.

Sign up to request clarification or add additional context in comments.

Comments

1

Iterator#next() is not a getter. It advances the pointer and returns the element at the new position.

Assign the value returned to a variable if you need to touch it twice:

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

while (iteratorUserRoles.hasNext()) {
    Role role = iteratorUserRoles.next();
    System.out.println(role.getName());
    // do something else with role
}

Comments

1

You are calling iterator.next() two times in while cycle. That's why you get exception (and why you miss second element)

However I would recommend you not to access iterator in this way. Use its mechanics in for loop like this.

for (com.liferay.portal.model.Role role : ruoli){
    System.out.println(role.getName());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.