ContainsAll array list issue Java -
so i'm trying use containsall built in list method compare 2 arrays
i used contains method single values , works perfectly, contains doesn't.
i'm making card game i'm checking whether set of cards in set of cards
so:
if(this.hand.containsall(hand.getcards())){
however statement keeps returning false..
here's constructor
private arraylist<card> hand; public hand(arraylist<card> hand) { this(); this.hand.addall(hand); }
here's cards method
public arraylist<card> getcards() { return this.hand; }
unsure why code isn't returning true containsall it's fine when done individually, there common concept haven't considered?
any pointers bonus
thank you
edit:
this returns true when used :
works
public boolean hascard(card card){ if (this.hand.contains(card)){ return true; } }
doesn't
public boolean hascards(hand hand){ if(this.hand.containsall(hand.getcards()){ return true } }
main..
card 1 = new card(card.rank.ace, card.suit.clubs); card 2 = new card(card.rank.ace, card.suit.diamonds); card 3 = new card(card.rank.two, card.suit.spades); card 4 = new card(card.rank.six, card.suit.randsuit()); card 5 = new card(card.rank.seven, card.suit.randsuit()); arraylist<card> cards = new arraylist<>(); cards.add(one); cards.add(two); cards.add(three); cards.add(four); cards.add(five); hand h = new hand(cards); card ones = new card(card.rank.ace, card.suit.clubs); card twos = new card(card.rank.ace, card.suit.diamonds); card threes = new card(card.rank.two, card.suit.spades); arraylist<card> cards2 = new arraylist<>(); // works h.hascard(five); // doesn't h.hascards(h2); cards2.add(ones); cards2.add(twos); cards2.add(threes); hand h2 = new hand(cards2);
try h.hascard(new card(card.rank.ace, card.suit.clubs))
. fill return false. h.hascard(one)
returns true.
to understand why, try this: one.equals(new card(card.rank.ace, card.suit.clubs)
. these 2 instances of same card, java has no way of knowing it. 2 different objects.
you added one
h
hand, so, when looking object, find it. searching object new card(card.rank.ace, card.suit.clubs)
fails, because java not know represents same card.
to fix this, have override equals
message on card
, , make return true objects correspond same card.
your containsall
call isn't working same reason: hand contains cards, represented different objects. implementing equals
method fix well.
Comments
Post a Comment