Java序列化问题:ArrayList添加Book时String转Author类型不兼容求助
问题描述
我尝试序列化多个对象,但向ArrayList<Book>添加元素时始终报错,books.add代码行提示不兼容的类型:String无法转换为Author。我试过把所有内容转成String但没用,想知道怎么把String转换成Author对象?我的目标是创建包含5个Book对象的ArrayList,涉及Author、Book、PubDate三个类,目前卡在Book类添加元素时的String转Author对象问题上。
相关代码
Book类
public class Book { private String bookTitle; private Author name; private PubDate date; public Book() { } public Book(String bookTitle, Author name, PubDate date) { this.bookTitle = bookTitle; this.name = name; this.date = date; } public String getBookTitle() { return bookTitle; } public Author getName() { return name; } public PubDate getDate() { return date; } public void setBookTitle(String bookTitle) { this.bookTitle = bookTitle; } public void setName(Author name) { this.name = name; } public void setDate(PubDate date) { this.date = date; } @Override public String toString() { return "Book{" + "bookTitle=" + bookTitle + ", name=" + name + ", date=" + date + '}'; } }
Author类
public class Author { private String firstname; private String lastname; private String title; public Author() { } public Author(String firstname, String lastname, String title) { this.firstname = firstname; this.lastname = lastname; this.title = title; } public String getFirstname() { return firstname; } public String getLastname() { return lastname; } public String getTitle() { return title; } public void setFirstname(String firstname) { this.firstname = firstname; } public void setLastname(String lastname) { this.lastname = lastname; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return "Author{" + "firstname=" + firstname + ", lastname=" + lastname + ", title=" + title + '}'; } }
Serialization类
public class Serialization { public static void main(String[] args) { ArrayList<Book> books = new ArrayList<Book>(); ArrayList<Author> authors = new ArrayList<Author>(); ArrayList<PubDate> pubs = new ArrayList<PubDate>(); books.add(new Book("Book Title", "Author Name", "Publishing Date")); } }
解决方案
问题出在你调用Book构造方法时,传入的第二个参数是字符串"Author Name",但构造方法要求的是Author类型的对象;第三个参数字符串"Publishing Date"也不符合PubDate类型的要求。要解决这个问题,你需要先创建Author和PubDate对象,再传入Book的构造方法。
1. 直接创建Author对象传入
如果知道作者的名、姓和头衔,直接用Author的构造方法实例化对象:
// 创建Author对象 Author author1 = new Author("John", "Doe", "Mr."); // 假设PubDate有类似的构造方法(根据你的PubDate类实现调整参数) PubDate pubDate1 = new PubDate("2024", "05", "20"); // 添加Book到集合 books.add(new Book("Book Title", author1, pubDate1));
2. 从单个字符串解析生成Author对象
如果只有类似"Author Name"的字符串,需要先拆分字符串提取作者信息,再创建对象。比如拆分出名和姓:
String authorStr = "Author Name"; String[] nameParts = authorStr.split(" "); // 假设拆分后第一个是名,第二个是姓,头衔默认空或自定义 Author author2 = new Author(nameParts[0], nameParts[1], ""); PubDate pubDate2 = new PubDate("2024", "05", "21"); books.add(new Book("Second Book", author2, pubDate2));
按照这个方式,你可以创建5个对应的Author和PubDate对象,逐个添加到books集合中。
内容的提问来源于stack exchange,提问作者Jermong
相关产品推荐
相关产品推荐

