简体   繁体   中英

Adding elements of different type to arraylist

So I have an arraylist which looks like this ArrayList<Card> player1Hand = Player.Player1(seed); It contains [KH, 9L, 7L, 8L, KE] Every combination represents one card. and an array split[] containing [KH]

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 . 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 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. Besides, a named constructor helps you to create a placeholder object based on value of split[2] . With this two steps you will be able to use contains and it will work as you want to. Why should you override a hashCode too? 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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