在抽象类集合中查找继承项
我有以下类:
public class CollectionCustomClass extends ArrayList<CustomClass>
public abstract class CustomClass
public class SubClass1 extends CustomClass
public class SubClass2 extends CustomClass
并且在一个方法中我想要执行以下操作:
CollectionCustomClass ccc = new CollectionCustomClass();
ccc.add(new SubClass1())
ccc.add(new SubClass2())
ccc.add(new SubClass1())
ccc.add(new SubClass2())
ccc.find(SubClass1)
结果将是 2 Subclass1。
我怎样才能做到这一点?
I have the following classes:
public class CollectionCustomClass extends ArrayList<CustomClass>
public abstract class CustomClass
public class SubClass1 extends CustomClass
public class SubClass2 extends CustomClass
and in a method i want to do the following:
CollectionCustomClass ccc = new CollectionCustomClass();
ccc.add(new SubClass1())
ccc.add(new SubClass2())
ccc.add(new SubClass1())
ccc.add(new SubClass2())
ccc.find(SubClass1)
The result would be the 2 Subclass1.
How can i achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尝试
并
Try
and
如果您想要确切类别的项目,只需对每个项目调用
getClass
并与您想要的类别进行比较。If you want items of the exact class, simply call
getClass
on each item and compare with the class that you want.如果我理解正确,您可以迭代 ArrayList 并进行以下比较:
If I understand you correctly, you can iterate through the ArrayList and do the following compare:
ArrayList 不包含 .find(Class) 方法。
http://download.oracle.com/javase/6 /docs/api/java/util/ArrayList.html
您需要在 CollectionCustomClass 上实现该方法。
在伪代码中,它会是这样的:
您还可以将泛型应用于此方法。
ArrayList does not contain a .find(Class) method.
http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html
You would need to implement that method on CollectionCustomClass.
In pseudo-code it would be something like this:
You could also apply generics to this method.
你可以在你的集合类中有 find 方法,如下所示
you can have find method in your collection class like this