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

标签 java arraylist interface

目前在获取数组列表中的特定对象时遇到问题。所以我有多个实现相同接口(interface)的类,我创建了不同类的对象。问题是我不知道如何区分数组列表中的类。

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

假设我想要获取 interfaceA(),我可以通过 arraylist.get(0) 调用它,但我不想对其进行硬编码。每个类都有相同的方法,但代码不同。

最佳答案

我会使用 Map 而不是 List。在这种情况下 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));
}

关于java - 在数组列表中查找特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49818254/

相关文章:

java - 如何将编码字符替换为字符串文字?像\uDXYZW 或者类似的东西?

java - 如何从另一个 JFrame 访问 ArrayList?

java - 如何删除值(value),确定剩余值(value)的最小值

linux - 是否可以计算 Linux 中每个接口(interface)发送/接收的 ICMP 数据包的数量?

java - 如何使用 f :ajax? 使 jsf 更改按下按钮后呈现的内容

java - Hibernate Native Query 性能不佳且难以转换为 JQPL

JAVA:Hashmap - 返回字符串数组列表

c# - 多态性不适用于 C# 中泛型类的调用

java - 为什么向 Java 接口(interface)添加新方法会破坏依赖旧版本的客户端?

java - Hibernate 对象在 AngularJS 和 Spring 中作为 @RequestBody