Java Program to create a user defined LinkedList class and store list of books and display
Program
import java.util.*;
class Book
{
String bname;
String author;
int price;
Book(String bname, String author, int price)
{
this.bname = bname;
this.author = author;
this.price = price;
}
public String toString()
{
String s = "Name = " + this.bname + "\tAuthor = " + this.author + "\tPrice = " + this.price;
return s;
}
}
public class BookListDemo
{
public static void main(String[] args)
{
LinkedList ll = new LinkedList();
ll.add(new Book("Java", "Herbert", 200));
ll.add(new Book("C", "Dennis", 150));
ll.add(new Book("C++", "Schildt", 350));
ll.add(new Book("Operating Systems", "Galvin", 500));
ListIterator litr;
System.out.println("********* Book Details **********");
for( litr = ll.listIterator(); litr.hasNext();)
System.out.println(litr.next() + "\t");
}
}
This Java program demonstrates creating a user-defined LinkedList class to store a list of books and display their details. It uses the Book class to represent book objects, and the LinkedList class from Java's java.util package to manage the collection of books.
-
Book Class:
- The
Bookclass represents the details of a book. It contains three attributes:bname: The name of the book.author: The author of the book.price: The price of the book.
- Represents book data with fields for name, author, and price.
- The overridden
toString()method provides a clear, readable output for theBookobjects. - The constructor initializes these attributes.
- The
toString()method is overridden to provide a formatted string representation of the book object.
- The
-
BookListDemo Class:
- The
mainmethod demonstrates the functionality. - A
LinkedListis created to store theBookobjects. - Java's
LinkedListis used to manage the list of books. - This dynamic data structure allows efficient insertion and iteration of elements.
- The
-
Adding Books:
- Several
Bookobjects are created and added to theLinkedListusing theadd()method.
- Several
-
Displaying the Books:
- A
ListIteratoris used to iterate through theLinkedListand display the details of each book using thetoString()method. - The
hasNext()method checks if there are more elements in the list, andnext()retrieves the next element.
- A
Output
********* Book Details **********
Name = Java Author = Herbert Price = 200
Name = C Author = Dennis Price = 150
Name = C++ Author = Schildt Price = 350
Name = Operating Systems Author = Galvin Price = 500