目前在获取数组列表中的特定对象时遇到问题。所以我有多个实现相同接口(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/