Tuesday, August 20, 2013

Restart iterator when finished

Restart iterator when finished

I have a list and I'd like to get the values at i-1, i and i+1 positions.
When i is the first or the last index, it would throw an
IndexOutOfBoundsException. To prevent that, I would write a few
if-statements and hardcode it like that:
if (i == 0){
a = list.get(list.size()-1);
b = list.get(0);
c = list.get(1);
} else if (i == list.size()-1){
a = list.get(i-1);
b = list.get(i);
c = list.get(0);
} else {
a = list.get(i-1);
b = list.get(i);
c = list.get(i+1);
}
I find this way is a littlebit static. Let's say I want to get n entries
from the list in this way, how would you do that?

No comments:

Post a Comment