Search⌘ K
AI Features

Solution: The Duplicate Detector

Understand how to define logical equality in Java by overriding the equals and hashCode methods. This lesson guides you through safely comparing objects based on unique identifiers, ensuring correct behavior in collections and duplicate detection scenarios.

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);
}
}
...