【问题标题】:Check If List Contains All Elements Of An Array [closed]检查列表是否包含数组的所有元素[关闭]
【发布时间】:2020-03-07 18:19:16
【问题描述】:

我正在尝试检查列表是否包含保存在数组中的所有值。

这是我的代码:

List<PlayingCard> playerDeck = new ArrayList<>();
playerDeck.add(PlayingCard.METAL);
playerDeck.add(PlayingCard.METAL);

public boolean canBuild(Item item) {
    return playerDeck.containsAll(Arrays.asList(item.requiredCards()));
}
public enum Item {
    ...

    public PlayingCard[] requiredCards() {
        return new PlayingCard[] {
            PlayingCard.METAL,
            PlayingCard.METAL,
            PlayingCard.METAL
        };
    }
}

我当前的 canBuild() 方法不会像这样工作。

playerDeck = [Metal] requiredCards = [Metal, Metal]
playerDeck.containsAll(requiredCards) == true

谁能帮帮我?

【问题讨论】:

    标签: java arrays list


    【解决方案1】:

    您没有正确声明您的枚举之一。并且不清楚您是否尝试在静态上下文中执行方法。请尝试以下操作:

    enum PlayingCard {
        METAL
    }
    
    enum Item {
        FOO;
    
        public PlayingCard[] requiredCards() {
            return new PlayingCard[] { PlayingCard.METAL,
                    PlayingCard.METAL, PlayingCard.METAL };
        }
    }
    
    static List<PlayingCard> playerDeck = new ArrayList<>();
    
    public static void main(String[] args) {
    
        playerDeck.add(PlayingCard.METAL);
        playerDeck.add(PlayingCard.METAL);
        Item foo = Item.FOO;
        System.out.println(canBuild(foo));
    
    }
    
    public static boolean canBuild(Item item) {
        return playerDeck
                .containsAll(Arrays.asList(item.requiredCards()));
    }
    

    更新:

     List<Integer> a = List.of(1,1,1);
     List<Integer> b = List.of(1,1);
     List<Integer> c = List.of(1,1,1);
     List<Integer> d = List.of(1,2,1);
     List<Integer> e = List.of(1,1,2);
     System.out.println(a.equals(b)); //false different count
     System.out.println(a.equals(c)); //true same numbers and count
     System.out.println(a.equals(d));// false same count, different numbers
     System.out.println(a.equals(e)); // false same numbers and count, different order
    

    【讨论】:

    • 我认为您没有正确理解我的问题。我的问题是我当前的 canBuild 方法没有考虑元素的数量。所以如果 playerDeck 只包含一个 METAL 项目而 item.requiredCards 包含 3x METAL,它仍然会返回 true。因此在这种情况下不能使用 containsAll。但是,我不确定我应该如何实现这个方法。感谢您尝试
    • 如果您有两个列表,并且它们具有相同顺序的相同值,如果有帮助,它们将比较相等。
    • 是的,但是如何比较两个具有不同数量的相同元素的列表呢?
    • 一个有金属,另一个有金属,金属。他们不应该平等比较。
    • 查看我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 2016-10-13
    相关资源
    最近更新 更多