So at school we are learning Java for the first time and we wanted to simulate a Java libray application where we have two classes named "Book" and another one name " and there can be no book with the same ISBN in the same shelf. So what i did was like the following inside of the shelf class and it works fine.
private boolean checkIsbnNumber(Book book){
boolean isbnTaken = false;
for(Book bList : this.bookList){
if(bList.getIsbn().equals(book.getIsbn())){
System.out.println("The books isbn number is taken");
isbnTaken = true;
}
}
return isbnTaken;
}
But what our lecturue told us to is the following, go on the book class and override the hash and the equals method to the following.
@Override
public boolean equals(Object obj) {
if (obj instanceof Book)
return isbn.equals(((Book)obj).isbn);
else
return false;
}
@Override
public int hashCode() {
int hash = 3;
hash = 53 * hash + Objects.hashCode(this.isbn);
return hash;
}
Then do the following inside of the shelf class once again.
public boolean checkISBN(Book b){
boolean isbnExists = false;
for (Book bList : bookList)
{
if(bList.getIsbn().equals(b.getIsbn())){
System.out.println("Book ISBN already exist");
isbnExists = true;
}
}
return isbnExists;
}
What i want to know is what is the point of doing it? is there any benefits over it? and why are we calling the equals method inside the equals method again? Some help would be greatly appreciated.