-2

Hi I am doing a poker game for my project. I have some problems figuring out how to test my contains() method. I know that you can type .contains("KING of SPADES"); for example but it does not work with my parameter. So what should I write instead? The same problem is with add2 I don't really know how to work with that (how to add a list and how to print it out) so can someone explain?

ArrayList<Card> PileOfCards;

public Pile(){
    PileOfCards = new ArrayList<Card>();
}

public void add(Card c){
    PileOfCards.add(c);
}

public void add2(List<Card> cards){
    PileOfCards.add((Card)cards);
}

public Boolean contains(Card c){
    return PileOfCards.contains(c);
}
Thomas Francois
  • 866
  • 6
  • 21
Zuzu
  • 19
  • 5
  • 1
    Your `PileOfCards` contains `Card` objects. The `contains` method thus wants that you pass in cars, not `String`s. Thus, it does not work with `String`s. You can either create a new card with that name and override `equals` for `Card`s (and `hashCode`). Or you setup a `Map` which associates names with cards. Then you have a fast direct access. Also note that `contains` in `List`s is very slow. Consider using a `Set` for this. – Zabuzard Sep 24 '18 at 15:55
  • so if I want to test my method what should I write? – Zuzu Sep 24 '18 at 15:56
  • 1
    Furthermore, your method `add2` is casting a List of Cards to a single Card. Does that compile?? – Robert Kock Sep 24 '18 at 16:03
  • Can you show the `Card` class? – Sweeper Sep 24 '18 at 16:05
  • @RobertKock actually it does, thats what I assumed that I have to write in the method – Zuzu Sep 24 '18 at 16:12
  • 1
    @RobertKock It compiles, because in theory, someone somewhere could write `public class BizarreCard extends Card implements List`. – VGR Sep 24 '18 at 18:17

2 Answers2

0

As far as your second question regards: Try this

public void add2(List<Card> cards)
{
  PileOfCards.addAll(cards);
}

This of course does not check eventual duplicates...

For the first question, we need your Card class.

Robert Kock
  • 5,795
  • 1
  • 12
  • 20
0
  • About your "add2()" problem:

You should use the addAll() method to append a list to another (@see documentation) And remove the cast operator (Card) cards, you are trying to transform a list of cards into a single card...

  • About the "contains()" method:

The List.contains method check if an object instance is included into a List, checking by references. So even if the parameter is a Card with the exact same attributes, it won't be considered as included in the list. Try to iterate over your list and check if the card title is the same as the one you are looping on (@see this thread). This might not be the best solution, as @Zabuza presented some possible ways, but you should start with that for the moment.

Kapcash
  • 6,377
  • 2
  • 18
  • 40