Hello everyone, I'm working through a Java course and I'm properly stuck on an exercise. I override equals so two listings with the same code are equal, yet a HashSet happily keeps both:
import java.util.HashSet;
import java.util.Set;
class Listing {
String code;
int price;
Listing(String code, int price) {
this.code = code;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Listing other)) return false;
return code.equals(other.code);
}
}
public class Main {
public static void main(String[] args) {
Set<Listing> set = new HashSet<>();
set.add(new Listing("A-1", 100));
set.add(new Listing("A-1", 100));
System.out.println(set.size()); // prints 2
}
}
What am I missing?