尝试用String和int填充对象的ArrayList。

时间:2018-10-20 12:35:04

标签: java arraylist

我的Book类包含三个字段-名称,作者和isbn
我正在尝试将字段插入ArrayList并打印:

book1, author1, isbn  
book2, author2, isbn2  
and... to 10

代码:

public class InsertBooks {

    private static ArrayList<String> booksNames = new ArrayList<>();
    private static ArrayList<String> booksAuthors = new ArrayList<>();
    private static ArrayList<Integer> booksIsbn = new ArrayList<>();
    private static ArrayList<Book> books = new ArrayList<>();

    // adding books in ArrayList booksNames
    private static void addBooksNames() {
        for (int i = 0; i < 10; i++) {
            booksNames.add("Book" + i);
        }
    }
    // adding author in ArrayList booksAuthors
    private static void addBooksAuthor() {
        for (int i = 0; i < 10; i++) {
            booksAuthors.add("Author" + i);
        }
    }
    // adding author in ArrayList booksAuthors
    private static void addBooksIsbn() {
        for (int i = 0; i < 10; i++) {
            booksIsbn.add(Integer.valueOf("isbn" + i));
        }
    }

    public static void fillArrayListOfBooks() {
        for (int i = 0; i < 10; i++) {
            books.add(new Book((addBooksNames(), addBooksAuthor(), addBooksIsbn()));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您要首先调用所有add*函数。然后在fillArrayListOfBooks()循环中使用这些值。

void fillArrayListOfBooks()
{
    addBooksNames();
    addBooksAuthor();
    addBooksIsbn();
    for (int i = 0; i < 10; i++) {
        dbooks.add(new Book(booksNames.get(i), booksAuthors.get(i), booksIsbn.get(i)));
    }
}

您可以轻松摆脱这些列表(除非以后需要它们):

void fillArrayListOfBooks()
{
    for (int i = 0; i < 10; i++) {
        dbooks.add(new Book("Book" + i, "Author" + i, "isbn" + i));
    }
}