从List1中删除值也会从List2中删除值?

时间:2011-06-08 05:59:43

标签: java arraylist

我想从ArrayList的副本中删除值而不影响原始副本。代码目前: statsOf2Pairs首先运行statsOfFullHouse,但是当我从statsOf2Pairs中的副本中删除它们时,原始列表的值已被删除。

public void statsOf2Pairs(List<List<Integer>> allRolls) {
        long count = 0;
        long debug = 0;
        List<List<Integer>> rolls = new ArrayList<List<Integer>>();
        rolls = allRolls;
        for (List<Integer> roll : rolls) {
            if(roll.size() < 5) {
                debug++;
            }
            if (hasMultiplesOf(roll, 2)) {
                roll.removeAll(Arrays.asList(mRepeatedDice));
                if (hasMultiplesOf(roll, 2)) {
                    count++;
                }
            }
        }
        System.out.println("The amount of 2 pairs in all the rolls possible: "
                + count);
        System.out.println("So the chance of rolling 2 pairs is: "
                + ((double) count / (double) mTotalPossibleRolls) * 100d + " %");
    }

    public void statsOfFullHouse(List<List<Integer>> allRolls) {
        long count = 0;
        long debug = 0;
        for (List<Integer> roll : allRolls) {
            if(roll.size() < 3) {
                debug++;
            }
            if (hasMultiplesOf(roll, 3)) {
                roll.removeAll(Arrays.asList(mRepeatedDice));
                if (hasMultiplesOf(roll, 2)) {
                    count++;
                }
            }
        }
        System.out.println("The amount of Full Houses in all the rolls possible: "
                + count);
        System.out.println("So the chance of rolling a Full House is: "
                + ((double) count / (double) mTotalPossibleRolls) * 100d + " %");
    }

2 个答案:

答案 0 :(得分:2)

我假设您要复制allRolls数组而不是将其分配给roll。 而不是

rolls = allRolls;

尝试

List<List<Integer>> rolls = new ArrayList<List<Integer>>(allRolls);

这将创建allRolls列表的新列表(浅拷贝)。最初的例子是将allRolls分配给roll,而不是复制它。

答案 1 :(得分:0)

通过执行roll = allRolls,您正在将allRolls arrayList的引用分配给roll。 因此,roll和allRolls都指向相同的arraylist,当你尝试从roll中删除一个值时,你实际上是从原始arraylist中删除。

相关问题