2010-09-14 32 views
4

我想将我的模型包装在主要用于ListView的ModelCollection中。该集合总是具有相同的属性,如title,totalResults(用于分页),并且它应包含ArrayList“items”中的listItem-Models。 但是,这些模型具有不同的类型,如“ModelCategory”或“ModelChain”,并且通常具有不同的属性和方法。Java:将不同类型的对象放入ModelCollection的ArrayList中。 Interaces?

如何在具有强大打字规则的java中实现这一目标?我的心界面是一个正确的方式来做到这一点。我在哪里必须执行它们?

public class ModelCollection { 

       public ArrayList< ModelCategory OR ModelChain OR ModelXyz> items = new ArrayList<ModelCategory OR ModelChain OR ModelXyz>(); 

       private String id; 
       private String title; 
       private Long updated; 

       private String linkSelf; 
       private int totalResults; 
       private int startIndex; 

    /* 
    more stuff like parsing a feed 
    */ 

    } 

回答

9

让你ModelCategory,ModelChain和ModelXyz实现一个接口。然后让你的收藏在这个界面上。

例如:

public interface MyModel { 
} 

public class ModelCategory implements MyModel { 
} 

List<MyModel> list = new ArrayList<MyModel>(); 

引用每个类的具体方法,你需要投你的列表对象为正确的类型。

List<MyModel> list = new ArrayList<MyModel>(); 
list.add(new ModelCategory()); 

ModelCategory model = (ModelCategory) list.elementAt(0); 

很明显,您可以使用您需要的任何方法来遍历您的集合。牛头人的

1

为所有模型类定义一个通用接口,它允许访问它们共享的属性。

public interface MooModel 
    String getTitle(); 
    // etc 

,并定义List<MooModel>

+0

好,以及如何代码看起来在我的视图控制器/活动?我如何访问ModelCategory的特殊方法? – OneWorld 2010-09-14 08:13:44

+1

使用“instanceof”关键字来检查你拥有的具体模型,然后将你的对象转换为特定的类。 – rompetroll 2010-09-14 08:28:36

+0

用于处理每个具体模型的特殊情况我会看看访问者模式:) – willcodejavaforfood 2010-09-14 08:28:45

5

解决方案是正确的,但记得要检查的instanceof像deadsven提出的,其结果是这样的:

List<MyModel> list = new ArrayList<MyModel>(); 
    list.add(new ModelCategory()); 

    for(MyModel mymodelListElement: list) { 
     //mymodelListElement.sameMyModelMethods() 

     if(ModelCategory instanceof mymodelListElement) { 
      ModelCategory modelCategoryElement = (ModelCategory)mymodelListElement; 
     } else if(ModelChain instanceof mymodelListElement) { 
      ModelChain modelChainElement = (ModelChain)mymodelListElement; 
     } else if(ModelXyz instanceof mymodelListElement) { 
      ModelXyz modelXyzElement = (ModelXyz)mymodelListElement; 
     } else { 
      //ignore 
      //or 
      //throw new RuntimeException("Wrong MyModel implementation") 
     } 

    } 
+0

您在if条件中颠倒语句...它应该是if(mymodelListElement instanceof ModelCategory).....希望它节省了某人的时间 – praveenb 2013-01-24 13:14:32

相关问题