Junior — Senior
Guaranteeing the uniqueness of objects in HashSet
livecode
Task condition
Two instances of the class Value with identical fields (a = 1, b = 1f) are placed into a HashSet<Value> collection. It is necessary to implement correct comparison and hashing methods in the Value class so that the HashSet perceives such objects as one and ensures the uniqueness of elements.
import java.util.HashSet;
import java.util.Set;
public class JetbulbInterview {
public static void main(String[] args) {
Set<Value> values = new HashSet<>();
Value v1 = new Value(1, 1f);
Value v2 = new Value(1, 1f);
values.add(v1);
values.add(v2);
System.out.println(values);
}
}
class Value {
int a;
float b;
public Value(int a, float b) {
this.a = a;
this.b = b;
}
@Override
public String toString() {
return "Value{" +
"a=" + a +
", b=" + b +
'}';
}
}