如何从测试器类访问/更改ArrayList?

时间:2015-12-09 21:10:19

标签: java arraylist

这个人让我在最近几个小时内陷入困境,我试图弄清楚如何访问存储在"图书馆"中的书籍对象的arraylist。从我的测试人员课程中,我确实有getter和setter,但我无法弄清楚我是如何从测试人员类中访问它们的。这是我的代码。

book.java

public class Book {
private int id;
private String bookTitle;
private String authorName;
private double bookReleaseYear;
private int numOnLoan;
private int numInStock;

//constructor
public Book(int id, String bookTitle, String authorName, double bookReleaseYear, int numOnLoan, int numInStock) {
    this.id = id;
    this.bookTitle = bookTitle;
    this.authorName = authorName;
    this.bookReleaseYear = bookReleaseYear;
    this.numOnLoan = numOnLoan;
    this.numInStock = numInStock;
}
//getters
//setters

Library.java

import java.util.ArrayList;
import java.util.Scanner;

public class Library {

public ArrayList<Book> books = new ArrayList<Book>();

//Constructor
public Library(ArrayList<Book> books) {
    this.books = books;
}
//Getters/setters

public ArrayList<Book> getBooks() {
    return books;
}

public void setBooks(ArrayList<Book> books) {
    this.books = books;
}

LibraryTester.java

import java.util.ArrayList;
import java.util.Scanner;
public class LibraryTester {

public static void main(String[] args) {

    Library<Book> book1 = new Library();
}

我已经谷歌搜索了几个小时,除非我碰巧错过了它,提前感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

我认为你在寻找的是:

Library library = new Library();
ArrayList<Book> books = library.getBooks();
Book book1 = books.get(0); //zero being the first index in the books array

假设我正确理解你的问题,那应该可以得到你所需要的东西。

答案 1 :(得分:1)

您可以同样访问Book列表,

public class LibraryTester {

public static void main(String[] args) {

    Library library= new Library();
    ArrayList<Book> listOfBooks = library.getBooks();

}

<强> EDITED

将以下构造函数添加到Library类中,

public Library(){
  super();
}