【发布时间】:2020-08-23 17:54:20
【问题描述】:
在我的question 用户@deadshot 上给我答案。
我决定对程序稍作改动。
我添加了一个对象 - ArrayList<int[]> combinations,它将用数字存储 array int[](此数组的大小始终为 3)。
我使用 add() 方法添加到 combinations 数组 (array[])。
package com.company;
import java.util.*;
public class Main {
static int POINTS_ON_LINE = 3;
public static void main(String[] args) {
int[] points = new int[]{1, 2, 3, 4};
System.out.println("no repetitions:");
p1(points, POINTS_ON_LINE);
}
public static void p1(int[] arr, int pointsOnLine) {
List<int[]> combinations = new ArrayList<>();
int lengthArray = arr.length, i;
int[] index = new int[pointsOnLine];
int[] temp = new int[pointsOnLine];
for (i = 0; i < pointsOnLine; i++) {
index[i] = i;
}
if (pointsOnLine < lengthArray) {
for (int j : index) {
temp[j] = arr[j];
}
boolean flag;
while (true) {
System.out.println("Add array: " + Arrays.toString(temp));
combinations.add(temp);
flag = false;
for (i = pointsOnLine - 1; i >= 0; i--) {
if (index[i] != i + lengthArray - pointsOnLine) {
flag = true;
break;
}
}
if (!flag) {
break;
}
index[i] += 1;
for (int j = i + 1; j < pointsOnLine; j++) {
index[j] = index[j - 1] + 1;
}
for (i = 0; i < pointsOnLine; i++) {
temp[i] = arr[index[i]];
}
}
System.out.println("End");
}
System.out.println("Result");
for(int[] q : combinations) {
System.out.println(Arrays.toString(q));
}
}
}
为什么是这样的结果:
no repetitions:
Add array: [1, 2, 3]
Add array: [1, 2, 4]
Add array: [1, 3, 4]
Add array: [2, 3, 4]
End
Result:
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
为什么对象combinations 包含:
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
[2, 3, 4]
但是对象combinations 应该包含这个:
[1, 2, 3]
[1, 2, 4]
[1, 3, 4]
[2, 3, 4]
【问题讨论】:
-
这是因为你修改了
temp。 -
@Nikolas,
ArrayList<int[]>不存储数组的HIS COPY? -
@Progman,是的,它看起来像这样。那么,我必须做些什么,以使值不会改变?
-
@n199a 您可以创建要保存的数组的副本。
标签: java