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
?
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);
@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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With