【发布时间】:2014-01-07 04:53:02
【问题描述】:
我对如何将多个值添加到数组列表中有些困惑。
我想要做的是将 1 个对象的多个值添加到数组列表中。
例如:
我有一个名为 books 的数组列表,我正在尝试添加一本书及其标题、作者、出版年份等...
这是我尝试过的地方,但我不确定它是否正确或是否有更简单的方法。
public class Book {
public static ArrayList<Book> Books = new ArrayList<>();
public int isbn;
public int yearPublished;
public String title;
public String author;
public String price;
public int noOfCopies;
Book b1 = new Book(1234, 1991, "Book1", "mark.mark", "£11.00", 5);
Book b2 = new Book(4321, 1994, "Book2", "bob.bob", "£12.00", 3);
public Book(int ISBN, int year, String ttle, String auth, String pri, int copies) {
this.isbn = ISBN;
this.yearPublished = year;
this.title = ttle;
this.author = auth;
this.price = pri;
this.noOfCopies = copies;
Books.add(this);
}
}
这是对的吗?谁能帮帮我
【问题讨论】:
-
您是否收到 StackOverflowError 错误?
-
您应该尊重命名约定。对于
Books.add(this);,我们的印象是add是Books类的静态方法。 -
删除 b1 和 b2 的定义