How could I have the index of an array 'roll over' when incrementing?

Viewed 13055

So I have an Array with a length of 4. When I increment it by 1 and the number gets bigger than the length of the array, I'd like it to rollover.

For example:

current_index = 3;
current_index++;
//current_index is now 0 again

current_index = 3;
current_index += 2;
//current_index would be 1

current_index = 0;
current_index--;
//current_index would be 3

I'm currently solving it with if-else like this

if (current_index == textviewlist.length + 1)
     current_index = 0;
else if (current_index == textviewlist.length + 2)
     current_index = 1;
else if (current_index == -1)
     current_index = 3;

But I feel like this isn't an appropriate solution, or "good" code.

Edit: I tried your suggestion, but apparently java behaves strangely with negative numbers. When I try

current_index = (current_index - 1) % textviewlist.length;

Java takes the index "0", decreases it by 1 ("-1") and then

 -1 % 4 = -1

I expected it to be 3, see Wolfram Alpha: -1 mod 4 But apparently the java % operator is not the same as the modulo operator?

Edit 2: I found a solution here: Best way to make Java's modulus behave like it should with negative numbers? - Stack Overflow

I can just do:

current_index -= 1;
current_index = (current_index % textviewlist.length + textviewlist.length)  % textviewlist.length;
4 Answers
Related