-1

this is my simply code in java:

 public class Book {
 private String title;
 private int year;

 public Book(String title, int year){
     this.title=title;
     this.year=year;
 }

 public String getTitle() {
     return title;
 }

 public int getYear() {
     return year;
 }
}
public class Library {

   private LinkedList listOfBooks=new LinkedList<Book>();

   public void addBook(Book book){
       listOfBooks.add(book);
   }

   public LinkedList getListOfBooks(){
       return listOfBooks;
   }
}
public class Application {

    public static void main(String[] args) {

        Library library=new Library();
        library.addBook(new Book("Title 1", 1995));
        library.addBook(new Book("Title 2", 2015));
        library.addBook(new Book("Title 3", 1998));
        library.addBook(new Book("Title 4", 2011));
        library.addBook(new Book("Title 5", 2020));
        library.addBook(new Book("Title 6", 2021));
        library.addBook(new Book("Title 7", 1999));

        Book book1=library.getListOfBooks().get(2);

    }
}

Why the " Book book1=library.getListOfBooks().get(2);" is wrong ? when I call library.getListOfBooks() I suppose to get LinkedList with Book Objects, so when I call: library.getListOfBooks().get(2) i suppose to get Book Object. Am I wrong ?

Angie0147
  • 1
  • 1
  • 1
    Does this answer your question? [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – OH GOD SPIDERS Jul 15 '21 at 12:55
  • 4
    You are using a raw type in `public LinkedList getListOfBooks()`. use `LinkedList` instead like you did in the declaration – OH GOD SPIDERS Jul 15 '21 at 12:55
  • 1
    The compiler prints warnings about your use of raw types. Pay attention to compiler warnings. Don’t just ignore them. – VGR Jul 15 '21 at 13:04

1 Answers1

1

You've used raw LinkedList in the Library class. That is why the getListOfBooks() returned linked list of objects, and the get(2) returned an object which you're trying to assign to the book1 variable.

Just modify the variable declaration and pass specific type to the linkedList, that'll work properly.

private LinkedList<Book> listOfBooks = new LinkedList<Book>();

Also change the return type of the function getListOfBooks:

public LinkedList<Book> getListOfBooks() {
    return listOfBooks;
}
devReddit
  • 2,696
  • 1
  • 5
  • 20