Restart the iterator upon completion

I have a list, and I would like to get the values ​​at positions i-1 , i and i+1 . When i is the first or last index, it would throw an IndexOutOfBoundsException . To prevent this from happening, I would write some if-statements and hardcode, like this:

 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 a little static. Say I want to get n entries from a list this way, how would you do it?

+4
source share
3 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 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()

  • Create a wrapper class that wraps indexes

+4
source

You can use the ternary operator to shorten the code a bit and adjust incoming calls to further reduce the code.

 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 need to process small lists (size () <= 2) to stop duplicate items.

+3
source

Why can't you just iterate over foreach and reassign old values ​​like this:

  List<Integer> list = Arrays.asList(1, 5, 7, 3, 4); int n = 3; // how much entries we take int a = 0, b = 0, c; for (int i = 0; i < n; i++) { c = b; b = a; a = list.get(i); // do some stuff } 
+1
source

Source: https://habr.com/ru/post/1497974/


All Articles