Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Modulus and wraparound (Negative Numbers)

807603Oct 18 2007 — edited Oct 18 2007
Hello,

I want to create an index that wraps around in a "*Ring*" type fashion. For instance,
{
    int index = 0;
    int[] array = new int[ 5 ];

    index = 0;
    index = (index - 1) % array.length;
    // index is now equal to '-1' however, I want it to wrap around to array.length -1

    index = 4;
    index = (index + 1) % array.length;
    // index is now equal to '0' and this is OK!
}
The statement "index = (index - 1) % array.length;" returns -1 when index == 0, however, I would like it to return 4; as it would in C Language. I know that Java modulus operator is different but is there an elegant way to do what I want to do? I was told to replace the statement with "index = ((index- 1) + array.length) % array.length;" this actually works but can the same result be achieved with fewer operations? I know that it is optimal compare to
    index = (index - 1);
    if (index < 0)
        index = array.length - 1;
but it would be nice if I can do it with fewer operations. Actually, I would not even have a problem is Java had "*unsigned int*".

I am willing to entertain any ideas and if nothing else I did get an understanding of Java handles '/' and why '%' functions the way it does!

Thanks!
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Nov 15 2007
Added on Oct 18 2007
4 comments
2,222 views