-2

I am a beginner in java and I have a problem.

I have to create a method to display the titles of the volumes 1 and 7 of Harry Potter. I tried with the get(int) method which is used to get the value of an element of an ArrayList but I get results that I don't understand.

Current code :

package tp.books;

import java.util.Arrays;
import java.util.List;

public class BookFactory {
    
    private List<Book> books = Arrays.asList(
            new Book(1, "Harry Potter à l'Ecole des Sorciers", "Que cache la trappe du troisième étage?"),
            new Book(2, "Harry Potter et la Chambre des Secrets", "Harry résoudra t'il le mystère de la chambre des secrets ?"),
            new Book(3, "Harry Potter et le Prisonnier d'Azkaban", "Qui est Sirius Black ?"),
            new Book(4, "Harry Potter et la coupe de feu", "Qui gagnera le tournoi des trois sorciers ?"),
            new Book(5, "Harry Potter et l'ordre du Phénix", "Harry et ses amis réussiront-ils à sauver Sirius Black (Harry en a rêvé)?"),
            new Book(6, "Harry Potter et le prince de sang mêlé", "Qui est le prince de sang-mêlé ?"),
            new Book(7, "Harry Potter et les reliques de la mort", "Harry parviendra t'il à retrouver tous les horcruxes et à les détruire ?")
            );

    public void printOnlyTome1AndTome7() {
        System.out.println("----- Titre des tomes -----");
        System.out.println(books.get(0));
        System.out.println(books.get(6));
    }

}

Current console :

----- Titre des tomes -----
tp.books.Book@5f205aa
tp.books.Book@6d86b085

What I would like in a console:

----- Titre des tomes -----
Harry Potter et la Chambre des Secret
Harry Potter et les reliques de la mort

Could someone point me to a solution that would allow me to get the right display titles?

Thank you in advance.

greg-449
  • 109,219
  • 232
  • 102
  • 145
  • 1
    You need to override toString() on your book object. – Michael Krause Nov 07 '21 at 14:26
  • If can suffix the get(0) with the field you want to get. If you want name the you have to give books.get(0).getName() – Ravi Korrapati Nov 07 '21 at 14:35
  • `books.get(0)` gives you the `Book` instance at index `0`. You need to print the title, not the book itself, so `books.get(0).getTitle()` or whatever method you have in that class. – QBrute Nov 07 '21 at 14:35
  • 1
    @beundead Great, thank you very much! I had no idea what to look for on the internet, this is exactly what I wanted and now it works perfectly! – Aaricia-Lila Nov 07 '21 at 14:41

2 Answers2

0

Thanks to everyone!

I was missing the toString() method in my Book.java class then I changed the books.get(0) to books.get(0).getTitle()

-1
class Book {

private Integer id;
private String value1;
private String value2;
//get/set

 @Override
  public String toString() {
    return getId() + "," + getValue1() + "," + getValue2();
  }

}

you also can use your IDE to generate it automatically or add Lombok(@Data) dependency

Eve
  • 37
  • 9