【发布时间】:2017-03-21 16:01:13
【问题描述】:
我在 ArrayList 中插入了一个数组,但在插入第二个数组后,第一个数组与第二个数组相同。
主类:
public static void main(String[] args) {
ArrayList<int[]> list = new ArrayList<>();
int[] parent = new int[4];
for (int i = 0; i < 2; i++) {
parent[0] = rand(4,1);
parent[1] = rand(6, -2);
parent[2] = rand(2, 1);
parent[3] = rand(-1, -2);
list.add(parent);
}
// to print the arrays of the parent
for (int i = 0; i < 2; i++) {
int[] arr ;
arr = list.get(i);
for (int j = 0; j < arr.length; j++) {
System.out.println("Value "+arr[j]);
}
System.out.println("Next Array");
}
Rand 函数 // 它是一个随机函数,在一个范围内生成随机值
public static int rand(int max,int min)
{
Random rand = new Random();
int value = 0;
return value = rand.nextInt(max + 1 - min) + min;
}
我已经运行了很多次,但是两个数组的值都是一样的。
我不明白为什么要得到两个数组的相同值。
【问题讨论】:
-
将
parent的定义移动到for循环中。 -
因为
int[]是一个对象,而不是原始值。您在列表中存储了两次相同的数组。 -
那是因为第一次添加到列表中的对象与第二次添加的对象相同。因此,它在 for 循环的第二次迭代期间被修改并打印了两次。
-
@Thomas 准备因为说 pass-by-reference 而受到攻击。攻击在 3...2...1...