Java添加在列表的末尾

时间:2012-07-27 10:30:47

标签: java arrays

我有一本书课。我想在列表的末尾添加一个元素

public class Book {
private String title;
private String authorName;
private double price;


/**
 * @param title
 * @param authorName
 * @param price
 */
public Book(String title, String authorName, double price) {
    setTitle(title);
    setAuthorName(authorName);
    setPrice(price);
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

public String getAuthorName() {
    return authorName;
}

public void setAuthorName(String authorName) {
    this.authorName = authorName;
}

public double getPrice() {
    return price;
}

public void setPrice(double price) {
    this.price = Math.abs(price);
}

}

和一个Booklist类,它有一个方法可以将书籍添加到列表中,但我无法弄清楚如何在列表中输入值

public class BookList {

/**
 * books will be stored in an array of strings
 */

private Book[] books;
// *** TODO *** you will need to add more private members variables

public BookList(int N) {
    // TODO Auto-generated method stub  
}



public void append(Book book) throws BookListFull {
    // TODO Auto-generated method stub 
}

}

我想在列表的末尾添加元素,请帮助我如何做到这一点 感谢

5 个答案:

答案 0 :(得分:1)

使用List<Book>代替Book数组。列表会在需要时自动增长。有关详细信息,请参阅collections tutorial

另外,修复代码中的注释:

/**
 * books will be stored in an array of strings <-- of strings?
 */
private Book[] books;

答案 1 :(得分:1)

1。我建议您使用Java的集合框架而不是Arrays。

2. 集合将为您提供大量灵活性和方法,因此您可以更具表现力的方式处理数据。

List<Book> list = new ArrayList<Book>;

<强>例如

     List<Book> list = new ArrayList<Book>;

     list.add(new Books(title, authorName, price));

答案 2 :(得分:0)

如果您无法使用List<Book>,则必须将现有数组复制到具有books.length +1的新数组中:

public void append(Book book) throws BookListFull {
    Book[] newArray = new Book[books.length + 1];
    for(int i = 0; i < books.length; i++){
        newArray[i] = books[i];
    }
    newArray[books.length] = book;
    books = newArray;
}

或者更轻松地使用List及其add()remove()方法。

答案 3 :(得分:0)

试试这个:

public void append(Book book) {
    Book[] buf = this.books;
    this.books = new Book[this.books.length + 1];
    for(int i = 0; i < buf.length; i++)
        this.books[i] = buf[i];
    this.books[buf.length + 1] = book;
}

答案 4 :(得分:0)

如果您因某种原因无法更改Book []书籍的类型(似乎您在构造函数中指定了最大大小):

  public void append(Book book) throws BookListFull {

    for (int i = 0; i < this.books.length; i++) {
        if (null == this.books[i]) {
            this.books[i] = book;
            return;
        }
    }
    throw new BookListFull();

}

也许您应该尝试将您的Exception的名称修改为BookListFullException或者其他东西 - 只需要我的2美分。