Trying to learn Java myself and am hitting a wall. I am not trying to override the equals method inherited from the Object class. I am trying to get the main method to compare the objects and not just compare the memory addresses of the reference variables (if that makes any sense). The exercise has a class called Book with name and publication year as the instance variables. Here is the method to test equality:
public boolean equals(Book compare) {
if (this == compare){
return true;
}
if (!(compare instanceof Book)){
return false;
}
Book compareBook = (Book) compare;
if (this.name == compareBook.name && this.publicationYear == compareBook.publicationYear){
return true;
}
return false;
In the main method I am asking for user input (name and publication year) and then using an IF statement and calling the "equals" method to see if what is being inputted is or is not already in an array list called "books".
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 addBook = new Book(name, publicationYear);
if (books.equals(addBook)) {
System.out.println("Let's not add the same book");
} else {
books.add(addBook);
System.out.println("Added...");
}
}
}
When I run the program I get the "Added..." response after entering a name and year. When I enter the same name and year it is supposed to say "Let's not add the same book.", but it doesn't. It just says "Added..." again until I enter a blank response.
What am I doing wrong?
I know this is probably an easy solution for experienced coders but for whatever reason I cannot crack this one. Trust me, I have tried a ton of things, searched the web, read over and over the section on objects as parameters and all that.
(This post has been edited once for clarification and to incorporate @SMA response.)