-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniqueBookSetDemo.java
More file actions
63 lines (50 loc) · 2.04 KB
/
Copy pathUniqueBookSetDemo.java
File metadata and controls
63 lines (50 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import java.util.HashSet;
import java.util.Objects;
// 1. The Book Class
class Book {
private String title;
private String author;
public Book(String title, String author) {
this.title = title;
this.author = author;
}
// Overriding equals() to ensure equality is based purely on title and author
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Book book = (Book) obj;
return title.equals(book.title) && author.equals(book.author);
}
// Overriding hashCode() to maintain the Java contract with equals()
@Override
public int hashCode() {
return Objects.hash(title, author);
}
public void display() {
System.out.println("\nTitle: " + title);
System.out.println("Author: " + author);
}
}
// 2. Main Driver Class (PascalCase)
public class UniqueBookSetDemo {
public static void main(String[] args) {
// Initialize the HashSet to store only unique Book objects
HashSet<Book> books = new HashSet<>();
System.out.println("--- Adding Books to the Library ---");
// Adding unique books
books.add(new Book("The Lord of the Rings", "J.R.R. Tolkien"));
books.add(new Book("Pride and Prejudice", "Jane Austen"));
books.add(new Book("To Kill a Mockingbird", "Harper Lee"));
// Adding duplicate books (These will be automatically ignored by the HashSet!)
books.add(new Book("The Lord of the Rings", "J.R.R. Tolkien")); // Duplicate
books.add(new Book("Pride and Prejudice", "Jane Austen")); // Duplicate
System.out.println("Books processed! Duplicates have been filtered out.");
System.out.println("\n--- Unique Books in the Set ---");
// Iterate through the HashSet and print the unique books
for (Book book : books) {
book.display();
}
System.out.println("\n-------------------------------");
}
}