package addingcustomobjectinlinkedlist; import java.util.LinkedList; import java.util.List; class Book { private String bookName; private int id; public Book(int id, String bookName) { super(); this.id = id; this.bookName = bookName; } public String getBookName() { return bookName; } public void setBookName(String bookName) { this.bookName = bookName; } public int getId() { return id; } public void setId(int id) { this.id = id; } } public class Example { public static void main(String[] args) { List<Book> listOfBook = new LinkedList<>(); listOfBook.add(new Book(3,"mahabharta")); listOfBook.add(new Book(2,"ramayana")); listOfBook.add(new Book(8,"alchemist")); listOfBook.add(new Book(4,"godan")); listOfBook.add(new Book(1,"panchtantra")); for(Book book: listOfBook) { System.out.println("book name is "+book.getBookName() +" " + ""+"book id is "+book.getId()); } } }
Output is –
book name is mahabharta book id is 3
book name is ramayana book id is 2
book name is alchemist book id is 8
book name is godan book id is 4
book name is panchtantra book id is 1