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

时间:2020-03-07 18:19:16

标签: java arrays list

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

这是我的代码:

$('td:contains("delete")').html("<i class='far fa-trash-alt' id='btnDelete'></i>").addClass("text-center delete delete:hover").on('click', function() {
        $("#delete-modal").modal('show');
        $("#btnDeleteConfirmation").on('click', function() {
            $(this).parents('tr').remove();
            $("#delete-modal").modal('hide');
          });
      });
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()));
}

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

public enum Item {
    ...

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

有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

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

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