简体   繁体   中英

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 {

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??? Does this part falls in Advance Java or do I need to revise my basics again? I'm confused with all these class Books passing as an argument thing

    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) {

Also please Explain why are we creating this below 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());




    }
}

Please Help Me...Thank you!

Generics

You asked:

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???

You need to learn about Generics in Java .

  • ArrayList is collection, a data structure for holding objects.
  • <Book> (after fixing your misnomer Books ) is telling the compiler that we intend to store only objects of the Book class in this particular collection.

If we mistakenly try to put a Dog object or an Invoice object into that collection, the compiler will complain. You will get an error message at compile-time explaining that only objects of the Book class can be put into that collection.

Also, you can put objects that are from a class that is a subclass of Book . Imagine you had HardCoverBook and SoftCoverBook classes that both extend from the Book class. Objects of those subclasses can also go into a collection of Book objects.

Other issues

Naming is important. Clear naming makes your code easier to read and comprehend.

So your class Books describes a single book. So it should be named in the singular, Book .

When collecting a bunch of book objects, such as a List , name that collection in the plural. For example List < Book > books .

Your book class could be more briefly written as a record . And we could shorten the names of your member fields.

record Book( String title, String author ) {}

We could shorten Ex7_LibraryManagementSystem to Library .

We need two lists rather than the one seen in your code. Given your scenario, we want to move books between a list for books on hand and a list of books loaned out.

More naming: The argument in your constructor should not be bookName , it should be something like initialInventory . And the type of that parameter should be simply Collection rather than specifically ArrayList or even List .

When passing in a collection of Book objects, copy them into our internally-managed lists. We don't want the calling code to be able to change the collection between our back. By making a copy, we take control.

For that matter, your books are not ordered, so no need for List . If the book objects are meant to be unique, we can collect them as Set rather than List — but I'll ignore that point.

Your addBooks adds only a single book, so rename in the singular.

"Issue" is an odd term; "loan" seems more appropriate to a library. Similarly, the issuedBooks method could use better naming, including not being in past-tense. Use date-time classes to represent date-time values, such as LocalDate for a date-only value (without time-of-day, and without time zone or offset). Mark those arguments final to avoid accidentally changing them in your method.

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

I recommend checking for conditions that should never happen, to make sure all is well. So rather than assume a book is on loan, verify. If things seem amiss, report.

After those changes, we have something like this.

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() );
    }
}

When run.

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM