1

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

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 类,它有一个方法 append 将书籍添加到列表中,但我无法弄清楚如何将值输入到列表中

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 
}

}

我想在列表末尾添加元素请帮我怎么做谢谢

4

6 回答 6

1

1.我会鼓励你使用Java 的Collection 框架而不是 Arrays。

2. Collection 会给你很大的灵活性和方法,所以你可以用更有表现力的方式处理你的数据。

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

例如:

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

     list.add(new Books(title, authorName, price));
于 2012-07-27T11:08:30.787 回答
1
public class BookList {
  List<Book> bookList= new ArrayList<Book>();

  ...
  ...
  public void append(Book book) throws BookListFull {
    bookList.add(book); 
  }
}
于 2012-07-27T10:34:26.637 回答
1

使用 aList<Book>而不是 Book 数组。列表会在需要时自动增长。有关更多信息,请参阅集合教程

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

/**
 * books will be stored in an array of strings <-- of strings?
 */
private Book[] books;
于 2012-07-27T10:36:19.623 回答
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();

}

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

于 2012-07-27T10:45:48.783 回答
0

如果您不能使用 a 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()

于 2012-07-27T10:34:58.477 回答
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;
}
于 2012-07-27T10:36:34.553 回答