我上课" Book"和班级"作者"在Java.Book和Author之间存在多对多的关系。
书籍课程:
public class Book
{
int ISPN;
String title;
String description;
int pageCount;
public ArrayList<Author> Authors;
}
作者类:
public class Author
{
int authorID;
String firstName;
String lastName;
ArrayList<Book> books;
}
我想序列化一本书或作者的对象,但是会有一个无限的递归,因为每本书都有他的相关作者的列表,他们有相关的书籍等无限。那么如何处理这样的情况?
抱歉我的英语不好。
答案 0 :(得分:0)
就你有多对多的关系而言,你需要有一些存储来存储所有数据(比如数据库)。恕我直言的最佳方法是让您列出transient并在还原可序列化时从此存储中恢复项目。如果你的情况确实是数据库,你可以使用一些内存缓存来加快速度。
<强> [编辑]:强>
以下是存储的替代实现:
<强> Storage.java 强>:
public class Storage implements Serializable {
private final HashMap<Integer, Book> books;
private final HashMap<Integer, Author> authors;
public Storage() {
books = new HashMap<>();
authors = new HashMap<>();
}
public void addBook(Book book) {
books.put(book.ISPN, book);
}
public void removeBook(Book book) {
books.remove(book.ISPN);
}
public void addAuthor(Author author) {
authors.put(author.authorID, author);
}
public void removeAuthor(Author author) {
authors.remove(author.authorID);
}
public Author getAuthor(Integer authorId) {
return authors.get(authorId);
}
public Book getBook(Integer bookId) {
return books.get(bookId);
}
}
<强> Book.java 强>:
public class Book implements Serializable {
int ISPN;
String title;
String description;
int pageCount;
ArrayList<Integer> AuthorIds;
Storage storage;
public Book(Storage storage) {
this.storage = storage;
}
public void addAuthor(Author author) {
storage.addAuthor(author);
AuthorIds.add(author.authorID);
}
public List<Author> createAuthorsList() {
List<Author> authorList = new ArrayList<>();
for (Integer authorId : AuthorIds) {
authorList.add(storage.getAuthor(authorId));
}
return authorList;
}
}
<强> Author.java 强>:
public class Author {
int authorID;
String firstName;
String lastName;
ArrayList<Integer> bookIds;
Storage storage;
public Author(Storage storage) {
this.storage = storage;
}
public void addBook(Book book) {
storage.addBook(book);
bookIds.add(book.ISPN);
}
public List<Book> createBooksList() {
List<Book> bookList = new ArrayList<>();
for (Integer bookId : bookIds) {
bookList.add(storage.getBook(bookId));
}
return bookList;
}
}
使用此实现的唯一(但很大)缺点是,在反序列化之后,您将拥有具有相同数据的多个Storage
类实例。为了优化这一点,我建议你将存储条目作为临时成员并单独序列化。