Java 在抽象类集合中查找继承项
我有以下课程:Java 在抽象类集合中查找继承项,java,class,collections,abstract,Java,Class,Collections,Abstract,我有以下课程: public class CollectionCustomClass extends ArrayList<CustomClass> public abstract class CustomClass public class SubClass1 extends CustomClass public class SubClass2 extends CustomClass 结果将是2个子类1 如何实现这一点?如果您想要精确类的项,只需对每个项调用getClass,并与您
public class CollectionCustomClass extends ArrayList<CustomClass>
public abstract class CustomClass
public class SubClass1 extends CustomClass
public class SubClass2 extends CustomClass
结果将是2个子类1
如何实现这一点?如果您想要精确类的项,只需对每个项调用
getClass
,并与您想要的类进行比较。如果我理解正确,您可以迭代ArrayList并执行以下比较:
if( listName.get(i).getClass() == passedClass ){ //increase count for this class }
ArrayList不包含.find(类)方法 您需要在CollectionCustomClass上实现该方法 在伪代码中,它是这样的:
public List CollectionCustomClass.find(CustomClassclazz) {
List<CustomClass> out = new ArrayList<CustomClass>();
// Loop through list and use instanceof to add items to out
return out;
}
公共列表集合CustomClass.find(CustomClassclazz){
List out=new ArrayList();
//循环浏览列表并使用instanceof将项添加到输出
返回;
}
您还可以将泛型应用于此方法。您可以在集合类中使用类似这样的find方法
public int find(String className) {
int count = 0;
for(int i=0; i<this.size();i++) {
if(className == this.get(i).getClass().getName()) {
count++;
}
}
return count;
}
public int find(字符串类名称){
整数计数=0;
对于(inti=0;iTry
及
class CollectionCustomClass扩展了ArrayList{
公共自定义类查找(类clazz){
对于(int i=0;i
公共集合CustomClass查找(Class clazz){
CollectionCustomClass答案=新建CollectionCustomClass();
对于(实体:本){
if(entity.getClass()==clazz){
答:增加(实体);
}
}
返回答案;
}
[code]public CollectionCustomClass find(Class clazz){CollectionCustomClass answer=new CollectionCustomClass();for(Entity Entity:this){if(Entity.getClass()==clazz){answer.add(Entity);}返回答案;}[/code]您的回答只返回了第一个对象,我必须找到所有的对象。啊!您正在尝试获取类型子类1的所有项;没有找到。是的,也无法获取注释代码的格式。感谢您提供的解决方案:)
public int find(String className) {
int count = 0;
for(int i=0; i<this.size();i++) {
if(className == this.get(i).getClass().getName()) {
count++;
}
}
return count;
}
ccc.find(SubClass1.class);
class CollectionCustomClass<T> extends ArrayList<CustomClass>{
public CustomClass find(Class<T> clazz) {
for(int i=0; i< this.size(); i++)
{
CustomClass obj = get(i);
if(obj.getClass() == clazz)
{
return obj;
}
}
return null;
}
}
public <T> CollectionCustomClass find(Class<T> clazz) {
CollectionCustomClass answer = new CollectionCustomClass();
for (Entity entity : this) {
if (entity.getClass() == clazz) {
answer.add(entity);
}
}
return answer;
}