简体   繁体   中英

Complex ArrayList with different type elements

I'm creating a complex data type. It's an ArrayList (chapters) of ArrayLists (chapter). 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...)?

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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