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:
You can use the modulo operator.
current_index = (current_index + n) % 4;
Just set it to itself modulo 4 - or rather, the length of the list - after each increment.
current_index += 2;
current_index %= textviewlist.length;
or combined:
current_index = (current_index + 2) % textviewlist.length;
You could also do this:
current_index += n;
while (current_index >= textviewlist.length) {
current_index -= textviewlist.length;
}
although I'd be surprised if that isn't slower than the modulo operation, especially since your list length is a power of 2.
Either way, it might be a good idea to encapsulate all this into an increment()
function:
int increment(int old_index, int n) {
return (old_index + n) % textviewlist.length;
}
EDIT: ah, I didn't realize you were working in Java. (I think C's modulo operator mimics the mathematical definition on negative numbers) A slight improvement on the solution you found would be
int increment(int old_index, int n) {
return (old_index + n + textviewlist.length) % textviewlist.length;
}
You can use mod as follows:
current_index = (current_index + i) % 4.
Divide the incremented index modulo the array's length:
current_index = (current_index + n) % textviewlist.length