简体   繁体   中英

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

For example (and this is very simplified), suppose I have a class for every card in a deck of cards... eg 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 (ie 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.

Try the instanceof operator:

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

@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
}

you can extend List like this:

public class XList<T> extends ArrayList {

    public boolean hasInstanceOf(Object obj) {
        for (Class<?extends Object> item: (Collection<Class<? extends Object>>)this ) {
            if (item.isInstance(obj)) return true;
        }
        return false;
    }

}

this solution allows you, that you can check for types dynamically instead of only static types.

you can implement the List like that:

xList<Class> classTypes = new xList<Class>();
if (classTypes.hasInstanceOf(item.getClass())){
    return true;
}

You can use following code:

private boolean findInstance(ArrayList items, String className) {
    boolean tag = false;
    for (int i = 0; i < items.size(); i++) {
        if (items.get(i).getClass().getName().equals(className)) {
            tag = true;
            break;
        }
    }
    return tag;
}

'className' includes package name, for example: 'java.lang.String'

public static <E> boolean containsInstance(List<E> list, Class<? extends E> clazz) {
    for (E e : list) {

        try {
            List<E> list2 = (List<E>) e;
            for (E list21 : list2) {
                System.out.println("<< ENCONTRO LISTA DENTRO DEL ARRAY DE OBJETOS >> ");
                if (clazz.isInstance(list21)) {
                    return true;
                }
            }
        } catch (Exception q) {
            System.out.println("<< ENCONTRO OBJETO DENTRO DEL ARRAY DE OBJETOS >> ");
            if (clazz.isInstance(e)) {
                return true;
            }
            continue;
        }

    }
    return false;
}

Checking the type of an object essentially breaks various object oriented principles. The question you may want to answer is that what do you plan to do once you find that type of object.

The action to be performed would be the verb which has to be modeled for each type. For example in a game of Solitaire when you click on a card you can put it on the stack on the right if it is an Ace. So that ability whether a card can land on the stack is determined by the object itself as it knows its identity. So essentially you have to implement a deal() method to each card and based on what the object it , it knows how the deal() has to be implemented for its instance. By doing it outside the object (and checking the type) you have essentially broken encapsulation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM