在arraylist中查找特定对象(Find specific object in an arraylist)

编程入门 行业动态 更新时间:2024-10-16 08:29:49
在arraylist中查找特定对象(Find specific object in an arraylist)

目前在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)); }

更多推荐

本文发布于:2023-07-22 09:47:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1219111.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   arraylist   Find   object   specific

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!