我无法理解 ArrayList 如何将 Class 对象作为数据类型

I cannot understand how an ArrayList can have Class object as a datatype

import java.time.LocalDate;
import java.util.ArrayList;

class Books{
    String bookName, authorName;
    public Books(String bName, String aName){
        this.authorName = aName;
        this.bookName = bName;
    }

    @Override
    public String toString(){
        return "Book Details{Book name: "+bookName+", Author: "+authorName+"}";
    }

}
public class Ex7_LibraryManagementSystem {

这是怎么回事?我是 java 的新手,所以我不太了解 ArrayList。我们是否正在创建一个具有 class 数据类型的 ArrayList???这部分是提前 Java 还是我需要再次修改我的基础知识?我对所有这些 class 作为参数传递的书感到困惑

    ArrayList<Books> booksList;
    Ex7_LibraryManagementSystem(ArrayList<Books> bookName){
        this.booksList = bookName;
    }

    public void addBooks(Books b){
        this.booksList.add(b);
        System.out.println("Book Added Successfully");
    }

    public void issuedBooks(Books b,String issuedTo,String issuedOn){
        if(booksList.isEmpty()){
            System.out.println("All Books are issued.No books are available right now");
        }
        else{
            if(booksList.contains(b))
            {
                this.booksList.remove(b);
                System.out.println("Book "+b.bookName+" is issued successfully to "+issuedTo+" on "+issuedOn);
            }
            else{
                System.out.println("Sorry! The Book "+b.bookName+" is already been issued to someone");
            }

        }

    }
    public void returnBooks(Books b, String returnFrom){
        this.booksList.add(b);
        System.out.println("Book is returned successfully from "+returnFrom+" to the Library");
    }


    public static void main(String[] args) {

另外请解释为什么我们要在下面创建 ArrayList

        ArrayList<Books> book1 = new ArrayList<>();
        LocalDate ldt = LocalDate.now();

        Books b1 = new Books("Naruto","Kisishima");
        book1.add(b1);

        Books b2 = new Books("Naruto Shippuden","Kisishima");
        book1.add(b2);

        Books b3 = new Books("Attack On Titan","Bhaluche");
        book1.add(b3);

        Books b4 = new Books("Akame Ga Kill","Killer bee");
        book1.add(b4);

        Books b5 = new Books("Death Note","Light");
        book1.add(b5);

        Ex7_LibraryManagementSystem l = new Ex7_LibraryManagementSystem(book1);
//        l.addBooks(new Books("Boruto","Naruto"));

        l.issuedBooks(b3,"Sanan",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
        l.issuedBooks(b1,"Sandy",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
//        l.issuedBooks(b2,"Suleman",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
//        l.issuedBooks(b4,"Sanju",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
//        l.issuedBooks(b5,"Thor",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());
        l.issuedBooks(b1,"anuj",ldt.getDayOfMonth()+"/"+ldt.getMonthValue()+"/"+ldt.getYear());




    }
}

请帮助我...谢谢!

泛型

您问的是:

ArrayList<Books> booksList;

What is going on here? I'm new to java so I don't get the ArrayList that much. Are we creating an ArrayList with a class datatype???

您需要了解 Generics in Java

  • ArrayList是集合,一种存放对象的数据结构。
  • <Book>(修正你的用词不当后 Books)告诉编译器我们打算在这个特定集合中只存储 Book class 的对象。

如果我们错误地尝试将 Dog 对象或 Invoice 对象放入该集合,编译器会报错。您将在 compile-time 处收到一条错误消息,说明只有 Book class 的对象可以放入该集合。

此外,您可以放置​​来自 class 的对象,该 class 是 Booksubclass。想象一下,你有 HardCoverBookSoftCoverBook class 都是从 Book class 扩展而来的。这些子 class 的对象也可以进入 Book 对象的集合。

其他问题

命名很重要。清晰的命名使您的代码更易于阅读和理解。

所以您的 class Books 描述了一本 单本 书。所以应该用单数命名,Book.

当收集一堆书籍对象时,例如 List,以复数形式命名该集合。例如 List < Book > books.

您的书 class 可以更简短地写成 record。我们可以缩短您的会员字段的名称。

record Book( String title, String author ) {}

我们可以将 Ex7_LibraryManagementSystem 缩短为 Library

我们需要两个列表,而不是您代码中看到的那个。根据您的情况,我们希望在手头图书列表和借出图书列表之间移动图书。

更多命名:构造函数中的参数不应该是 bookName,它应该类似于 initialInventory。并且该参数的类型应该只是 Collection 而不是具体 ArrayList 甚至 List.

传入 Book 对象的集合时,将它们复制到我们的 internally-managed 列表中。我们不希望调用代码能够更改我们之间的集合。通过制作副本,我们掌控一切。

就此而言,您的书没有订购,因此不需要 List。如果书籍对象是唯一的,我们可以将它们收集为 Set 而不是 List — 但我会忽略这一点。

您的addBooks只添加了一本书,所以用单数重命名。

“问题”是个奇怪的词; “借”似乎更适合图书馆。同样,issuedBooks 方法可以使用更好的命名,包括不在 past-tense 中。使用 date-time classes 表示 date-time 值,例如 LocalDate 表示 date-only 值(没有 time-of-day,也没有时区或偏移量).标记这些参数 final 以避免在您的方法中意外更改它们。

loanBook ( final Book book , final String borrower , final LocalDate dateLoaned ) { … }

我建议检查不应该发生的情况,以确保一切正常。因此,与其假设一本书是借出的,不如核实一下。如果事情看起来不对劲,请报告。

经过这些更改后,我们有这样的东西。

package work.basil.example.lib;

import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;

record Book( String title , String author )
{
}

public class Library
{
    private List < Book > booksOnHand, booksOnLoan;

    Library ( Collection < Book > initialInventory )
    {
        this.booksOnHand = new ArrayList <>( initialInventory );
        this.booksOnLoan = new ArrayList <>( this.booksOnHand.size() );
    }

    public void addBook ( Book b )
    {
        this.booksOnHand.add( b );
        System.out.println( "Book added successfully." );
    }

    public void loanBook ( final Book book , final String borrower , final LocalDate dateLoaned )
    {
        if ( this.booksOnHand.isEmpty() )
        {
            System.out.println( "All Books are issued. No books are available right now." );
        }
        else
        {
            if ( this.booksOnHand.contains( book ) )
            {
                this.booksOnHand.remove( book );
                this.booksOnLoan.add( book );
                System.out.println( "Book " + book.title() + " by " + book.author() + " is loaned to " + borrower + " on " + dateLoaned );
            }
            else if ( this.booksOnLoan.contains( book ) )
            {
                System.out.println( "Sorry! The Book " + book.title() + " by " + book.author() + " is out on loan." );
            }
            else
            {
                System.out.println( "ERROR – We should never have reached this point in the code. " );
            }
        }
    }

    public void returnBook ( Book book , String returnFrom )
    {
        if ( this.booksOnLoan.contains( book ) )
        {
            this.booksOnLoan.remove( book );
            this.booksOnHand.add( book );
            System.out.println( "The Book " + book.title() + " by " + book.author() + " has been returned to the Library." );
        }
        else
        {
            System.out.println( "The Book " + book.title() + " by " + book.author() + " is not out on loan, so it cannot be returned to the Library." );
        }
    }

    public String reportInventory ( )
    {
        StringBuilder report = new StringBuilder();
        report.append( "On hand: " + this.booksOnHand );
        report.append( "\n" );
        report.append( "On load: " + this.booksOnLoan );
        return report.toString();
    }

    public static void main ( String[] args )
    {
        List < Book > stockOfBooks =
                List.of(
                        new Book( "Naruto" , "Kisishima" ) ,
                        new Book( "Naruto Shippuden" , "Kisishima" ) ,
                        new Book( "Attack On Titan" , "Bhaluche" ) ,
                        new Book( "Akame Ga Kill" , "Killer bee" ) ,
                        new Book( "Death Note" , "Light" )
                );
        Book b1 = stockOfBooks.get( 0 ), b2 = stockOfBooks.get( 1 ), b3 = stockOfBooks.get( 2 );

        Library library = new Library( stockOfBooks );

        library.loanBook( b3 , "Sanan" , LocalDate.now() );
        library.loanBook( b1 , "Sandy" , LocalDate.now().plusDays( 1 ) );
        library.loanBook( b2 , "anuj" , LocalDate.now().plusDays( 2 ) );
        library.returnBook( b1 , "Sandy" );

        System.out.println( library.reportInventory() );
    }
}

当运行.

Book Attack On Titan by Bhaluche is loaned to Sanan on 2022-04-19
Book Naruto by Kisishima is loaned to Sandy on 2022-04-20
Book Naruto Shippuden by Kisishima is loaned to anuj on 2022-04-21
The Book Naruto by Kisishima has been returned to the Library.
On hand: [Book[title=Akame Ga Kill, author=Killer bee], Book[title=Death Note, author=Light], Book[title=Naruto, author=Kisishima]]
On load: [Book[title=Attack On Titan, author=Bhaluche], Book[title=Naruto Shippuden, author=Kisishima]]