Java 如何在自定义对象中正确实现领域列表?
因此,我试图在我的类中实现一个领域列表,但是,我可以在上找到的文档并没有阐明它是否需要getter/setter,以及它是否实现了应有的功能。这是我的代码:Java 如何在自定义对象中正确实现领域列表?,java,android,realm,Java,Android,Realm,因此,我试图在我的类中实现一个领域列表,但是,我可以在上找到的文档并没有阐明它是否需要getter/setter,以及它是否实现了应有的功能。这是我的代码: public class Novel extends RealmObject { @PrimaryKey private static int id; @Required private static String name; //Establish relationship with Novel (si
public class Novel extends RealmObject {
@PrimaryKey
private static int id;
@Required
private static String name;
//Establish relationship with Novel (single) and Chapter (many)
private RealmList<Chapter> chapters;
public static int getId() {
return id;
}//end getId
public static void setId(int id) {
Novel.id = id;
}//end setId
public static String getName() {
return name;
}//end getName
public static void setName(String name) {
Novel.name = name;
}//end setName
}//end Novel.class
getter看起来不错,但是setter对于如何正确使用RealmList
对我来说毫无意义
tldr:我的getter/setter应该是什么才能在我的自定义对象中正确实现
RealmList
?RealmList
实现所有有用的接口:
java.lang.Iterable<E>, java.util.Collection<E>, java.util.List<E>
如果要用新章节替换所有章节:
RealmList<Chapter> chapters = new RealmList<Chapter>();
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters = realm.copyToRealm(chapters);
novel.setChapters(chapters);
RealmList chapters=newrealmlist();
章节。添加(新章节());
章节。添加(新章节());
章节。添加(新章节());
章节。添加(新章节());
chapters=realm.copyToRealm(chapters);
小说。集章(章);
我理解这些东西,但这并不能回答我的问题。我不确定我的自定义对象文件(在本例中为Novel.java)中的RealmList的getter/setter必须是什么。您的setter/getter在您的问题中是可以的。RealObject(和RealmList)只是代理对象。这意味着您只能使用它来访问/修改字段,并且应该以这种方式声明它们。谢谢你的帮助!
Chapter chapter = realm.copyToRealm(new Chapter());
novel.getChapters().add(chapter);
RealmList<Chapter> chapters = new RealmList<Chapter>();
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters.add(new Chapter());
chapters = realm.copyToRealm(chapters);
novel.setChapters(chapters);