Java:将不同类型的对象放入 ModelCollection 的 ArrayList 中。接口(interface)?

标签 java interface types arraylist

我想让我的模型包含在一个 ModelCollection 中,它主要用于 ListView。该集合始终具有相同的属性,如标题、totalResults(用于分页),并且它应包含 ArrayList“项目”中的 listItem-Models。 但是,这些模型具有不同的类型,如“ModelCategory”或“ModelChain”,并且通常具有不同的属性和方法。

我如何在具有强类型规则的 java 中实现这一点?我心目中的接口(interface)是执行此操作的正确方法。我必须在哪里实现它们?

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
    */

    }

最佳答案

让您的 ModelCategory、ModelChain 和 ModelXyz 实现一个接口(interface)。然后将您的 Collection 放在该界面上。

例如:

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);

显然,您可以使用任何需要的方法来遍历您的集合。

关于Java:将不同类型的对象放入 ModelCollection 的 ArrayList 中。接口(interface)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3707097/

相关文章:

java - 如果运行 JSF 应用程序时未通过 Maven 添加,IntelliJ 是否不使用外部 Jar?

c# - IShell shell = new ... 和 Shell shell = new 有什么区别

Python - 从字符串创建矩阵

java - 我如何指定一个同时匹配 String 和 long 的类型?

c++ - 可变参数模板类中的定义数量不同

java - 如何将 org.apache.poi 添加到 Karafa

java - log4j.properties 中的 rootCategory 是什么意思?

java - maven 没有下载我添加的任何依赖项

java - 在程序中应用接口(interface)和抽象类的概念

C# 相当于 VB6 'Type'