我正在尝试创建一个简单的方法来将数组中的第一个元素移动到数组的后面。
这是我的代码
public class Ex5_ShiftLeft {
public static void main(String[] args) {
int[] a = new int[] {6, 2, 5, 3};
swap (a);
}
public static void swap(int[] array){
array[0] = array[array.length];
System.out.println(Arrays.toString(array));
}
}
Eclipse 似乎没有检测到我的代码的错误,但是当我运行它时,我收到错误文本
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4 at apollo.exercises.ch04_loops.Ex5_ShiftLeft.swap(Ex5_ShiftLeft.java:19) at apollo.exercises.ch04_loops.Ex5_ShiftLeft.main(Ex5_ShiftLeft.java:1)"
有什么建议吗?
最佳答案
数组代表程序保留的一段内存,用于存储一系列数字或数组拥有的任何其他内容。因此,数组不能调整大小;您不能超出您保留的内存段的末尾,因为另一个程序可能正在使用该内存。您的解决方案不起作用,因为它尝试获取第一个元素并将其放在数组末尾之后,这是超出范围的。相反,您必须记住第一个元素,然后将除第一个空格之外的每个元素向左移动以在数组末尾留出空间,然后您可以将第一个元素放在数组末尾。
关于java - 移动数组中元素的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27630178/