Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Shift/Rotate Object Array

My question should actually be really simple: I have an object array of Players.(players[]) I want to have a function that rotates this array until an index:

public void rotateArray(Object[] array, int index)

This would convert

{Player1, Player2, Player3, Player4, Player5}

with an index of 2 to:

{Player3, Player4, Player5, Player1, Player2}

But I want to prevent issues with references. I've tried System.arraycopy() but either I was to dumb to get it working or I is the wrong method for this.

like image 513
VoidCatz Avatar asked Nov 29 '22 01:11

VoidCatz


1 Answers

This one-line solution rotates the array in-place, with constant extra memory and linear time:

Collections.rotate(Arrays.asList(array), -index);
like image 51
Louis Wasserman Avatar answered Dec 09 '22 13:12

Louis Wasserman