Search code examples
javaobjectarraylistequalscontains

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) {
        this.name = 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.name.equals(comparedBook.name)
                && 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()) {
        break;
    }
    System.out.println("Publication year:");
    int publicationYear = Integer.valueOf(scanner.nextLine());
    Book book = new Book(name, publicationYear);
    if (!(books.contains(book))) {
        books.add(book);
    }

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


Solution

  • You can’t change the signature of Object.equals(Object).

    You should use the @Override annotation to catch this kind of error. See tutorial by Oracle.

    @Override
    public boolean equals(Object compared) {
        if (this == compared) {
            return true;
        }
        if (!(compared instanceof Book)) {
            return false;
        }
        Book comparedBook = (Book) compared;
        if (this.name.equals(comparedBook.name)
                && this.publicationYear == comparedBook.publicationYear) {
            return true;
        }
        return false;
    }