简体   繁体   English

将不同类型的元素添加到 arraylist

[英]Adding elements of different type to arraylist

So I have an arraylist which looks like this ArrayList<Card> player1Hand = Player.Player1(seed);所以我有一个 arraylist 看起来像这个ArrayList<Card> player1Hand = Player.Player1(seed); It contains [KH, 9L, 7L, 8L, KE] Every combination represents one card.它包含[KH, 9L, 7L, 8L, KE]每个组合代表一张牌。 and an array split[] containing [KH]和一个包含[KH]的数组split[] ]

Now I tried this: if (player1Hand.contains(split[2])) {//code} Now the if statement does not get executed since split[] contains objects of type String and the arrayList contains objects of type Card .现在我尝试了这个: if (player1Hand.contains(split[2])) {//code}现在 if 语句没有被执行,因为 split[] 包含 String 类型的对象,而 arrayList 包含Card类型的对象。 Is there an easy way to fix this?有没有简单的方法来解决这个问题?

You should create a named constructor (from Effective Java J.Bloch) for your Card class and override equals and hashCode for it like this:您应该为您的卡 class 创建一个命名构造函数(来自 Effective Java J.Bloch),并像这样覆盖equalshashCode

class Card {
    private String valueAsString;

    /*your code here*/
    
    public static Card of(String valueAsString) {
         Card card = /*create your card here*/
         card.valueAsString = valueAsString;
         return card;
    }

    @Override
    public boolean equals(Object other) {
         /*another part of equals*/
         return Objects.equals(valueAsString, other.valueAsString);
    }

    @Override
    public int hashCode() {
         return Objects.hash(valueAsString);
    }
}

With that named constructor you can just do the following thing:使用该命名构造函数,您可以执行以下操作:

    if (player1Hand.contains(Card.of(split[2]))) {
         /*do something*/
    }

The explanation: as soon as ArrayList uses an equals method to compare elements in the array you need to define it properly.解释:只要ArrayList使用equals方法比较数组中的元素,您就需要正确定义它。 Besides, a named constructor helps you to create a placeholder object based on value of split[2] .此外,命名构造函数可帮助您根据split[2]的值创建占位符 object 。 With this two steps you will be able to use contains and it will work as you want to.通过这两个步骤,您将能够使用contains ,它会按照您的意愿工作。 Why should you override a hashCode too?为什么你也应该覆盖hashCode You should do it, because there is an informal rule that you should always override equals and hashCode like a pair, because they have to do it's stuff with the same set of fields.您应该这样做,因为有一条非正式规则,您应该始终像一对一样覆盖equalshashCode ,因为它们必须使用相同的字段集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM