2011-03-26 46 views
0

我有以下类别:查找抽象类集合继承项目

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。

我该如何做到这一点?

回答

0

尝试

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; 
    } 
} 
+0

[代码]公共 CollectionCustomClass找到(类clazz){ \t CollectionCustomClass answer = new CollectionCustomClass(); \t为(实体实体:本){ \t \t如果(entity.getClass()== clazz所){ \t \t \t answer.add(实体); \t \t} \t \t} return answer; } [/ code] 你的答案只返回第一个对象,我不得不找到所有的对象。 – 2011-03-26 22:06:53

+0

啊!您正试图获取SubClass1类型的所有项目;错过了。 – 2011-03-26 22:08:29

+0

是的,无法获得评论代码的格式。感谢您的解决方案:) – 2011-03-26 22:09:23

0

如果您想要确切的课程的项目,只需在每个项目上调用getClass并与您想要的课程进行比较。

0

如果我理解正确的话,您可以通过迭代ArrayList中,做以下对比:

if(listName.get(i).getClass() == passedClass){ //increase count for this class } 
0

ArrayList中不包含.find(Class)方法。

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html

你会需要实现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; 

} 

您也可以申请仿制药这种方法。

0

你可以找到方法在集合类这样

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; 
    } 
0
public <T> CollectionCustomClass find(Class<T> clazz) { 
    CollectionCustomClass answer = new CollectionCustomClass(); 
    for (Entity entity : this) { 
     if (entity.getClass() == clazz) { 
      answer.add(entity); 
     } 
    } 
    return answer; 
}