0

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?

2
  • You can use a Map<String,Card> instead of ArrayList<Card> and use map.containsKey(split[2]) Commented Dec 21, 2021 at 9:31
  • Additionally, does Card have an String constructor? You could do player1hand.contains(new Card(split[2])). It is possible that you need to overload equals for this approach Commented Dec 21, 2021 at 9:33

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.