Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart iterator when finished

Tags:

java

list

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?

like image 917
Gaeburider Avatar asked Feb 16 '23 12:02

Gaeburider


2 Answers

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

like image 116
tom Avatar answered Feb 20 '23 10:02

tom


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.

like image 33
Husman Avatar answered Feb 20 '23 09:02

Husman