我正在尝试克隆第一个数组。
它有时会抛出 ArrayIndexOutOfBoundsExpection
?为什么会发生这种情况,我该如何解决?
import java.util.Random;
public class CloneArray {
public static void main(String args[]) {
Random rand = new Random();
int[] arr = new Random().ints(16, 1, 16 + 1).sorted().toArray();
int[] clone = arr;
for (int element: arr) {
System.out.println(arr[element]);
}
System.out.println("---Clone the Array----");
//clone the array
for (int ele: clone) {
System.out.println(clone[ele]);
}
}
}
最佳答案
要真正克隆数组,您应该使用 .clone()
方法。 (请注意,这仅适用于一维数组。)使用 for each loop ,您应该简单地打印 ele
而不是尝试使用数组的元素作为索引。
int[] arr = new Random().ints(16, 1, 16 + 1).sorted().toArray();
int[] clone = arr.clone();
//...
for (int ele: clone) {
System.out.println(ele);
}
关于java - 尝试克隆数组时出现 ArrayIndexOutOfBoundsExcetion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62735557/