I want to understand the logic of looping through a list. When I reach the end of list, I want the index to start from 0 again. The list is running in a loop and termination will happen, so it will not be an infinite loop.
I have seen solution using % operator but I don't understand it. Something like below but with % instead. I want to understand how that will work.
for(int i = 0; i < n; i++) {
if(i == n - 1) { i = 0; }
}
The modulo operator %
is the remainder after a division.
Given two positive numbers, a and n, a % n is the remainder of the Euclidean division of a by n, where a is the dividend and n is the divisor.
You said you have a list, if you use % list.length()
this will give you values from 0 to list.length().
See the following code:
List<String> list = new ArrayList<String>();
list.add("first");
list.add("second");
list.add("third");
for (int i = 0; i < 10; i++) {
System.out.println("element: " + list.get(i % list.size()));
}
this outputs:
element: first
element: second
element: third
element: first
element: second
element: third
element: first
element: second
element: third
element: first
You can check it working here.