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?
You can use (i-1+list.size()) % list.size()
and (i+1) % list.size()
.
This will also handle lists of length 1.
Heavier options:
Write a method
<T> T get(List<T> list, int i)
{
i %= list.size();
return list.get(i >= 0 ? i : i + list.size());
}
Subclass and override get()
Make a wrapper class which wraps around indices
You could use the ternary operator to shorten the code a little, and factor out the get calls to shorten the code further.
int prev, i, next;
//start loop here
prev = (i == 0 ? list.size()-1 : i-1);
next = (i == list.size()-1 ? 0 : i+1);
a = list.get(prev);
b = list.get(i);
c = list.get(next);
// end loop here
You will have to handle small lists, (size() <= 2) to stop repeating elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With