I have a LinkedList
of objects in Java
and I want to iterate through it, and when I find a specific object there - I want to take the next object (the one that is right next to the first one).
I thought this would solve the case:
listIterator = items.listIterator();
while (listIterator.hasNext() && listIterator.previous().getCode().equals(search.getCurrentCode())) {
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
but I'm getting error:
java.util.NoSuchElementException: null
I think it's because of using .previous
, but I don't know how to handle that correctly, how could I solve it then? I'm using previous
, but what I want is to use the current element - I thought that's handled by .previous
, but apparently it's not.
Your current code fails because You are calling previous, before even start iterating on items. Iteration is done with listIterator.next();
call.
You can try the code below.
while (listIterator.hasNext()){
// iterate always
item = listIterator.next();
// if found and an element still exist
if(item.getCode().equals(search.getCurrentCode() && listIterator.hasNext()){
// get the next element
item = listIterator.next();
result.setCurrentCode(item.getCode());
break;
}
}