目前在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); }假设我想获得interfaceA() ,我可以通过arraylist.get(0)调用它,但我不想对其进行硬编码。 每个类都有相同的方法,但代码是不同的。
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<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. Each class has the same methods but the code is different.
最满意答案
我会使用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)); }I would use a Map instead of a List. In this case an IdentityHashMap is a good fit.
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)); }更多推荐
发布评论