java - 一个数组中有多个变量?

标签 java arraylist

我正在学习 Java 入门类(class),其中我正在构建一个小型图书馆系统,图书馆员可以通过该系统添加书籍、列出所有书籍并搜索特定书籍。

它现在可以工作,但是在一本书的 ArrayList 中只有标题。我想添加 ISBN、作者、出版年份及其在图书馆中的当前状态。如何在同一个 ArrayList 中添加变量? 下面是我的 ArrayList;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

//Array form available books

public final class ListBook {


    public static List<String> VALUES = new ArrayList<String>(Arrays.asList(
             new String[] {"Book1","Book2","Book3","Book4"} 
    ));
}

本例中的另一个重要类允许图书管理员添加一本新书;

public class InsertBook {

    // variables for the book info
    public String name_book;

    // Importing the list of books
    ListBook lb = new ListBook();
    // variable for the list of books
    private int x;

    // Constructors
    Scanner input_name = new Scanner(System.in);

    public void insertDataBook() {
        System.out.println("----------------------------------------");
        System.out.println("Write your book title:");

        name_book = input_name.next();
        System.out.println("----------------------------------------");
        System.out.println("The following value was added");
        System.out.println(name_book);
        System.out.println("----------------------------------------");

        lb.VALUES.add(name_book);

        // To iterate through each element, generate a for so the array comes to
        // a list. Through the variable x.
        for (x = 0; x < lb.VALUES.size(); x++) {
            System.out.println(lb.VALUES.get(x));
        }

    }

}

应该怎样做?

最佳答案

您不希望拥有一个仅包含标题的“字符串”ArrayList,而是需要一个包含对象的ArrayList。考虑以下因素:

class Book {
    public String ISBN;
    public String author;
    public String year;

    public Book(String ISBN, String author, String year) {
        this.ISBN = ISBN;
        this.author = author;
        this.year = year;
    }
}

然后您可以按如下方式添加到此列表:

List<Book> VALUES = new ArrayList<Book>();
Book b = new Book("1234", "Name", "1984");
VALUES.add(b);

关于java - 一个数组中有多个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29196042/

相关文章:

java - 请帮助...我在 Java 中计算素数的实现是否在做它应该做的事情?

java - 在 ArrayList 中计数 - Java

java - Gson反序列化生成NULL值

java - 划分 ArrayLists 输出

java - 从一个线程多次调用同步方法

java - 在 ListView 中加载共享首选项

java - 循环迭代等待 repaint() 方法完成

java - 保存一些数据然后检索它的最佳方法

java - 在FreeRTOS上使用Java?

java - 添加动画时 Android 应用程序停止