Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, how can I check if a collection contains an instance of a specific class?

Tags:

java

generics

For example (and this is very simplified), suppose I have a class for every card in a deck of cards... e.g. a KingOfSpaces class, a QueenOfSpades class, a JackOfDiamonds class, etc. All of which that extend Card. There might be multiple instances of KingOfSpaces.

And I have an ArrayList<Card>, with 5 objects in it. How can I check to see if that ArrayList contains at least one AceOfDiamonds?

like image 776
Philihp Busby Avatar asked Oct 12 '11 02:10

Philihp Busby


3 Answers

Let's start out by pointing out that using classes for this sort of differentiation is almost certainly a bad thing. I'd say that you probably need to make 'Card' be a bit more intelligent (i.e. having a getSuit() and getOrdinal() method).

But, if you insist on doing it that way, iterate the array list (you can google that - it's a pretty basic thing) and compare each entry in the list using the instanceof operator.

You tagged this question as having to do with 'reflection', which doesn't seem right. Are you sure you didn't mean to flag it 'homework' ?

OK - what the heck, here's the code:

List<Card> hand = ...;
for(Card card : hand){
  if (card instanceof AceOfDiamonds) return true;
}

but please don't set up your class hierarchy like that - it's horrible design.

like image 175
Kevin Day Avatar answered Oct 04 '22 15:10

Kevin Day


Now you can do this with streams in a really simply, one-liner way:

List<Card> myList = fillitSomehow();
myList.stream().anyMatch(c -> c instanceof AceOfDiamonds);
like image 26
Carrol Avatar answered Oct 04 '22 17:10

Carrol


@Daniel Pereira answers the question as asked. I'd like to propose that what you really want is an enum.

Examples:

enum Card {
    KingOfSpades,
    QueenOfSpades,
    JackOfSpades,
    // etc
    AceOfDiamonds;
}

Card myCard = ...;
if(myCard == Card.KingOfSpades) {
    // stuff
}

Set<Card> cards = new EnumSet<Card>(Card.class);
cards.add(...);
if(cards.contains(myCard)) {
   // stuff
}
like image 5
Brendan Long Avatar answered Oct 04 '22 16:10

Brendan Long