[Solved] How to correctly initialize a list member object in Java


The first constructor:

public Book(String bookname, String authorName) {
    mBookName = bookname;
    mAuthorName = authorName;
    mPageList = new ArrayList<>();
}

Then you will have a new book without any page

The second constructor:

public Book(String bookname, String authorName, List<Page> pageList) {
    mBookName = bookname;
    mAuthorName = authorName;
    mPageList = pageList;
}

You will have a new book with pages referenced to the pages (Might be in DB).

Since the arraylist in java is muttable , any changed data will be modified to the original data (See here Java Immutable Collections)

If you are going to used the data without any change to the origin data(Just copy) , you might should use the immutable collection to avoid this problem. But if you are going to used it with some modification ( I saw the class is extended SugarRecord), the second constructor will be alright for you.

2

solved How to correctly initialize a list member object in Java