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

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.


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);

Try the instanceof operator:

if (myObject instanceof myType) {
    System.out.println("myObject is an instance of myType!");
}

Tags:

Java

Generics