开发者

Removing values from List1 also removes values from List2?

I want to remove values from a copy of an ArrayList without affecting the original copy. Code currently: statsOf2Pairs runs first then statsOfFullHouse, but the original list is has its values removed when I remove them from a copy in 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 + " %");
    }


I assume you are wanting to copy the allRolls array instead of assign it to rolls. Instead of

rolls = allRolls;

Try

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

This will create a new list (shallow copy) of the allRolls list. The original example was assigning the allRolls to rolls, not copying it.


By doing rolls = allRolls you are assinging the reference of the allRolls arrayList to rolls. Therefore both rolls and allRolls points to same arraylist and when you try to remove one value from rolls you are actually removing from the orginal arraylist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜