gpt4 book ai didi

java - 尝试克隆数组时出现 ArrayIndexOutOfBoundsExcetion

转载 作者:行者123 更新时间:2023-12-02 16:35:58 24 4
gpt4 key购买 nike

我正在尝试克隆第一个数组。它有时会抛出 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com