Java – Rotating array

Add a modulo array length to your code:

// create a newArray before of the same size as array

// copy
for(int x = 0; x <= array.length-1; x++){
  newArray[(x+a) % array.length ] = array[x];
}

You should also create a new Array to copy to, so you do not overwrite values, that you’ll need later on.

Leave a Comment