【问题标题】:Why elements are added incorrectly in List<int[]> in Java? [duplicate]为什么在 Java 的 List<int[]> 中错误地添加了元素? [复制]
【发布时间】:2020-08-23 17:54:20
【问题描述】:

在我的question 用户@deadshot 上给我答案。

我决定对程序稍作改动。
我添加了一个对象 - ArrayList&lt;int[]&gt; 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&lt;int[]&gt; 不存储数组的HIS COPY
  • @Progman,是的,它看起来像这样。那么,我必须做些什么,以使值不会改变?
  • @n199a 您可以创建要保存的数组的副本。

标签: java


【解决方案1】:

改变这一行:

combinations.add(temp); 

到这里:

combinations.add(Arrays.stream(temp).toArray());

这将获取当前状态的数组副本,并将其添加到列表中。这是使用来自 java 8 的流 api。

【讨论】:

  • 我这样做了java combinations.add(Arrays.copyOf(temp, temp.length)); 。但是,谢谢。
猜你喜欢
  • 2012-10-06
  • 1970-01-01
  • 2015-05-29
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 2012-11-28
  • 2022-01-18
  • 1970-01-01
相关资源
最近更新 更多