gpt4 book ai didi

java - 检查列表是否包含数组的所有元素

转载 作者:行者123 更新时间:2023-12-01 18:04:25 25 4
gpt4 key购买 nike

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

这是我的代码:

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

有人可以帮我吗?

最佳答案

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

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

关于java - 检查列表是否包含数组的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60580808/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com