【问题标题】:How to correctly initialize a list member object in Java如何在 Java 中正确初始化列表成员对象
【发布时间】:2016-12-22 07:38:13
【问题描述】:

我有这门课:

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;
    }

}

Page 类不多,但以防万一:

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;
    }
}

现在我认为有两个构造函数是有意义的,一个用于如果您已经有页面,一个用于如果您没有,但这是正确的方法吗?还是我需要复制进入构造函数的 ArrayList 而不是仅仅引用它?

【问题讨论】:

  • 这行得通——对我来说看起来不错。复制列表的内容是一种选择,但不是必需的。您是否遇到了让您认为这是错误的问题?
  • @Krease SugarORM 左右向我抛出错误,也许这就是原因
  • 什么样的错误?
  • table BOOK has no column named M_PAGE_LIST (code 1): , while compiling: INSERT OR REPLACE INTO BOOK(ID,M_AUTHOR_NAME,M_PAGE_LIST,M_BOOK_NAME) VALUES (?,?,?,?) 即使在我重新安装应用程序之后

标签: java android list oop constructor


【解决方案1】:

第一个构造函数:

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;
}

您将拥有一本新书,其中的页面引用了这些页面(可能在 DB 中)。

由于java中的arraylist是可变的,任何改变的数据都会被修改成原来的数据(看这里Java Immutable Collections

如果您要使用数据而不对原始数据进行任何更改(只需复制),您可能应该使用不可变集合来避免此问题。但是如果你打算使用它进行一些修改(我看到这个类是扩展的 SugarRecord),第二个构造函数对你来说没问题。

【讨论】:

  • Remember, write your own custom method to update the "Book" db and referenced "Page" DB both (if you have) 什么意思?
  • 这是我的失败,我错误地认为 SugarRecord 会有类似 ActiveRecord github.com/pardom/ActiveAndroid/wiki/Saving-to-the-database 的东西。如果要更新两个有关系的表,则必须调用两次
猜你喜欢
  • 1970-01-01
  • 2011-07-14
  • 1970-01-01
  • 1970-01-01
  • 2014-10-13
  • 1970-01-01
  • 1970-01-01
  • 2021-09-07
  • 2016-05-03
相关资源
最近更新 更多