我想让我的模型包含在一个 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/