Search⌘ K
AI Features

Solution: The Duplicate Detector

Explore how to define logical equality for Java objects by overriding equals to compare key fields like product IDs and maintaining hashCode consistency. Understand the importance of reference checks, type validation, and adhering to equality contracts to implement reliable duplicate detection.

We'll cover the following...
Java 25
import java.util.Objects;
public class InventoryApp {
static class Product {
private int id;
private String name;
public Product(int id, String name) {
this.id = id;
this.name = name;
}
// 1. Override equals to compare IDs
@Override
public boolean equals(Object obj) {
// Self-check
if (this == obj) return true;
// Null and Type check
if (obj == null || getClass() != obj.getClass()) return false;
// Cast and Compare
Product other = (Product) obj;
return this.id == other.id;
}
// 2. Override hashCode to match equals
@Override
public int hashCode() {
// Simple approach: return the unique ID
return Objects.hash(id);
}
}
public static void main(String[] args) {
Product p1 = new Product(101, "Gaming Laptop");
Product p2 = new Product(101, "Gaming Laptop");
System.out.println("Comparison Result:");
System.out.println("p1.equals(p2): " + p1.equals(p2));
boolean hashMatch = p1.hashCode() == p2.hashCode();
System.out.println("Hash codes match: " + hashMatch);
}
}
...