equals and hashCode
Completed
Create Book(String title, String author) and override equals and hashCode so books with the same title and author are equal. Read n books (title;author) into a HashSet and print how many distinct books there are.
Input
n, then n lines title;author.
Output
The number of distinct books.
Example
Input
4 Dune;Herbert Emma;Austen Dune;Herbert Dune;Someone
Output
3
Editor
Java
Hints
HashSet uses hashCode first, then equals.
Equal objects must have equal hash codes.
Solution explanation
Without these overrides, two separate Book objects are never equal, so the set keeps duplicates.
Show solution
import java.util.HashSet;
import java.util.Objects;
import java.util.Scanner;
import java.util.Set;
class Book {
final String title, author;
Book(String title, String author) {
this.title = title;
this.author = author;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Book)) return false;
Book b = (Book) o;
return title.equals(b.title) && author.equals(b.author);
}
@Override
public int hashCode() {
return Objects.hash(title, author);
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().trim());
Set<Book> books = new HashSet<Book>();
for (int i = 0; i < n; i++) {
String[] p = sc.nextLine().split(";");
books.add(new Book(p[0].trim(), p[1].trim()));
}
System.out.println(books.size());
}
}