简体   繁体   English

在数组列表中查找特定对象

[英]Find specific object in an arraylist

Currently have an issue getting a specific object in an arraylist. 当前在数组列表中获取特定对象时遇到问题。 So I have multiple classes that implements the same interface, and I create objects of the different classes. 因此,我有多个实现相同接口的类,并创建了不同类的对象。 The problem is that I don't know how to differentiate the classes in the arraylist. 问题是我不知道如何区分arraylist中的类。

ArrayList<Interface> arraylist = new ArrayList<>();

public static void main(String[] args) {

    addInterface(new interfaceA());
    addInterface(new interfaceB());
    addInterface(new interfaceC());

}

public static void addInterface(Interface foo) {
    arraylist.add(foo);
}

Let say that I want to get interfaceA() , I could call it by arraylist.get(0) but I don't want to hardcode it. 假设我要获取interfaceA() ,可以通过arraylist.get(0)调用它,但是我不想对其进行硬编码。 Each class has the same methods but the code is different. 每个类具有相同的方法,但代码不同。

You could filter using a predicate, by checking runtime classes: 您可以通过检查运行时类使用谓词进行过滤:

List<Interface> interfaceAList = arraylist.stream()
                         .filter(e -> InterfaceA.class.isInstance(e))
                         .collect(Collectors.toList());

I would use a Map instead of a List . 我将使用Map而不是List In this case an IdentityHashMap is a good fit. 在这种情况下, IdentityHashMap非常适合。

interface Thing {

}

IdentityHashMap<Class<? extends Thing>, Thing> things = new IdentityHashMap<>();

class ThingA implements Thing {
    @Override
    public String toString() {
        return "ThingA{}";
    }
}

class ThingB implements Thing {
    @Override
    public String toString() {
        return "ThingB{}";
    }
}

class ThingC implements Thing {
    @Override
    public String toString() {
        return "ThingC{}";
    }
}

public void registerThing(Thing thing) {
    things.put(thing.getClass(), thing);
}

public void test(String[] args) {
    registerThing(new ThingA());
    registerThing(new ThingB());
    registerThing(new ThingC());

    System.out.println(things.get(ThingB.class));
}
    public Interface getInterfaceA(List<Interface> interfaces) {
    for (Interface i : interfaces) {
        if (i instanceof InterfaceA)
            return i;
    }
    return null;
    }

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

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