简体   繁体   English

在Java中,如何检查集合是否包含特定类的实例?

[英]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 . 例如(这是非常简化的),假设我有一张卡片中的每张卡片的类......例如KingOfSpaces类, QueenOfSpades类, JackOfDiamonds类等等。所有这些都扩展了Card There might be multiple instances of KingOfSpaces . KingOfSpaces可能有多个实例。

And I have an ArrayList<Card> , with 5 objects in it. 我有一个ArrayList<Card> ,里面有5个对象。 How can I check to see if that ArrayList contains at least one AceOfDiamonds ? 如何查看该ArrayList包含至少一个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). 我要说你可能需要让'Card'更聪明一些(即使用getSuit()和getOrdinal()方法)。

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. 但是,如果你坚持这样做,迭代数组列表(你可以google - 这是一个非常基本的东西)并使用instanceof运算符比较列表中的每个条目。

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: 试试instanceof运算符:

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

@Daniel Pereira answers the question as asked. @Daniel Pereira按要求回答了这个问题。 I'd like to propose that what you really want is an enum . 我想提出你真正想要的是一个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: 你可以像这样扩展List:

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: 你可以像这样实现List:

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' 'className'包含包名,例如:'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. 所以基本上你必须为每张卡实现一个deal()方法,并根据它的对象,它知道如何为它的实例实现deal()。 By doing it outside the object (and checking the type) you have essentially broken encapsulation. 通过在对象外部进行(并检查类型),您实际上已经破坏了封装。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查一个类的特定实例是否在java中运行? - how to check if a specific instance of a class is running in java? 如何检查一组对象是否包含 object,该 object 的特定字段在 Java 中有特定值? - How can I check if a Set of objects contains an object having a specific fields with a specific value in Java? 如何检查 ArrayList 是否包含具有特定字段值的对象? - How can I check if an ArrayList contains an Object with a specific field value? JAVA:如何使用对象包装实例将ArrayList初始化为特定的类类型? - JAVA: How can I initialize an ArrayList to specific class type with Object-wrapped instance? 如何检查元素是否包含特定的类属性 - How to check if element contains specific class attribute 如何检查 hashmap 是否包含自定义 class 类型的密钥? - How can I check if a hashmap contains a key of a custom class type? 如何检查使用JMockit传递的特定模拟实例? - How can I check a specific mocked instance is passed using JMockit? 在包含私有集合的类上使用迭代器错误“只能迭代数组或java.lang.Iterable的实例” - Error “Can only iterate over an array or an instance of java.lang.Iterable” using iterator on a class that contains a private collection 如何检查Java映射包含的数据类型? - How can I check what type of data a java map contains? 在Java中,类可以引用包含它的另一个类的实例吗? - In Java, can a class reference the instance of another class which contains it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM