我正在编写一个代码,将数组的所有元素移回一个,并将最后一个元素移动到数组的前面.
我非常希望我的程序能够这样做:
int[] array = new int[] {1, 2, 3};
// do something such that array will become {3, 1, 2}
Run Code Online (Sandbox Code Playgroud)
我的代码如下:
int[] array = new int[3];
for(int i = 0; i < array.length; i++)
{
  array[0] = 1;
  array[1] = 2;
  array[2] = 3;
  int last = array[array.length-1];
  array[i] = array[i+1];
  array[0] = last;
  System.out.println(array[i]);
}
Run Code Online (Sandbox Code Playgroud)
我认为为数组添加1到"i",并将数组的最后一个元素存储在"last"中并将其分配给array [0]就可以了,但我只是得到了{3,3}输出"java.lang.ArrayIndexOutOfBoundsException:3".
如果您真正想要的是旋转它(听起来有点像).使用Collections.rotate():
Collections.rotate(Arrays.asList(array), 1);
Run Code Online (Sandbox Code Playgroud)
其中1是步数(距离)
如果您不想将数组转换为列表,可以使用这样的简单方法手动旋转(例如)
向左走:
void rotateArrayLeftByOne(int array[])
{
    // get last index of array
    int lastIndex = array.length - 1; 
    // save first element
    int oldFirst = array[0]; 
    // copy the elements from  right to left
    for (int i = 0; i < lastIndex; i++) 
        array[i] = array[i + 1];
    // put the first element last
    array[lastIndex] = oldFirst;
}
Run Code Online (Sandbox Code Playgroud)
并向右:
void rotateArrayRightByOne(int array[])
{
    // get last index of array
    int lastIndex = array.length - 1; 
    // save last element
    int oldLast = array[lastIndex]; 
    // copy the elements from  left to right
    for (int i = lastIndex; i != 0; i--) 
        array[i] = array[i - 1];
    // put the last element first
    array[0] = oldLast;
}
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           2404 次  |  
        
|   最近记录:  |