How to correctly initialize a list member object i

2019-09-21 22:47发布

I have this class:

public class Book extends SugarRecord {
    private Long id;
    private String mBookName;
    private String mAuthorName;
    private List<Page> mPageList;

    public Book() {

    }

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

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

    @Override
    public Long getId() {
        return id;
    }

    @Override
    public void setId(Long id) {
        this.id = id;
    }

    public String getAuthorName() {
        return mAuthorName;
    }

    public void setAuthorName(String authorName) {
        mAuthorName = authorName;
    }

    public String getBookName() {
        return mBookName;
    }

    public void setBookName(String bookName) {
        mBookName = bookName;
    }

}

The Page class isn't much but just in case:

public class Page {
    private Long id;
    private String mText;

    public Page() {

    }
    public Page(String text) {
        mText = text;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getText() {
        return mText;
    }

    public void setText(String text) {
        mText = text;
    }
}

Right now I figure it makes sense to have two constructors, one for if you have pages already and one if you don't, but is this the right way to go about it? Or do I need to copy the ArrayList that comes into the constructor as opposed to merely referencing it?

1条回答
三岁会撩人
2楼-- · 2019-09-21 23:25

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.

查看更多
登录 后发表回答