简体   繁体   English

具有不同类型元素的复杂ArrayList

[英]Complex ArrayList with different type elements

I'm creating a complex data type. 我正在创建一个复杂的数据类型。 It's an ArrayList (chapters) of ArrayLists (chapter). 它是ArrayLists(章节)的ArrayList(章节)。 However, there are two versions of the chapter, each with it's respected elements and data types. 但是,本章有两个版本,每个版本都有受尊重的元素和数据类型。

How could I declare my complex data type so I could add one or another (to have, eg, ArrayList(chapters) which contains (chapter_typeI,chapter_typeII,chapter_typeII,chapter_typeI,chapter_typeII, etc...)? 我如何声明我的复杂数据类型,以便我可以添加一个或另一个(例如,包含(chapter_typeI,chapter_typeII,chapter_typeII,chapter_typeI,chapter_typeII等...)的ArrayList(章节)?

make an abstract class, from which the both type of chapters inherit, and then declare a list of this type. 创建一个抽象类,从中继承这两种类型的章节,然后声明这种类型的列表。

public abstract class AbstractChapter {}

public class ChapterTypeOne extends AbstractChapter {}

public classs ChapterTypeTwo extends AbstractChapter {}

List<AbstractChapter> chapters = new ArrayList<AbstractChapter>;

The operations that you are going to call should be declared in the abstract class, and then overriden as necessary in the specific implementations. 您要调用的操作应在抽象类中声明,然后在特定实现中根据需要覆盖。

It is always better to create List of types than actual object if you have clear hierarchy defined. 如果您定义了明确的层次结构,那么创建类型列表总是比实际对象更好。

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

Now Type can be your interface 现在Type可以是您的界面

interface Type {
    void method();
}

Now you can have 现在你可以拥有

SubType1 implements Type {
    void method() {
        // do something.
    }
}

SubType2 implements Type {
    void method() {
        // do something.
    }
}

Also you can use Abstract Skeletal pattern in which you can have class AbstractType with default implementation if required 您还可以使用Abstract Skeletal模式,如果需要,您可以在其中使用类AbstractType和默认实现

最好的方法是使用继承来定义抽象类“Chapter”,并从抽象类派生章节类型。

你可以有一个抽象的基类“Chapter”,从中继承ChapterI和ChapterII。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM