How to stop adding objects given by the user to an arraylist if they already gave it?

This is the class

public class Book {
    private String name;
    private int publicationYear;
    public Book(String name, int publicationYear) { = name;
        this.publicationYear = publicationYear;
    public boolean equals(Book compared) {
        if (this == compared) {
            return true;
        if (!(compared instanceof Book)) {
            return false;
        Book comparedBook = (Book) compared;
        if (
                && this.publicationYear == comparedBook.publicationYear) {
            return true;
        return false;

I tried doing this in the main

while (true) {
    System.out.println("Name (empty will stop):");
    String name = scanner.nextLine();
    if (name.isEmpty()) {
    System.out.println("Publication year:");
    int publicationYear = Integer.valueOf(scanner.nextLine());
    Book book = new Book(name, publicationYear);
    if (!(books.contains(book))) {

So if the user keeps giving a book with the same name and year the program adds them to the list still

Read more here:

Content Attribution

This content was originally published by wuazap1 at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: