r/learnjava • u/vegan_antitheist • Oct 16 '26
Can you answer this question about Java sets and floating point numbers?
What does this return?
static int test(Set<BigDecimal> set) {
assert set.isEmpty();
set.add(new BigDecimal("-0"));
set.add(new BigDecimal("0"));
set.add(new BigDecimal("0.0"));
set.add(new BigDecimal("0.00"));
return set.size();
}
Hint: The Set interface says that elements a and b are unique when a.equals(b) returns true. However, not all implementations use equals.
Answer: A HashSet will contain three elements ([0, 0.0, 0.00]). -0 and 0 are the same, but 0.0 isn't equal to 0 or 0.00. A TreeSet on the other hand uses a Comparator and it will contain only one element ([0]). Try this by creating two sets (HashSet and TreeSet) and then run for (var set : List.of(hash, tree)) IO.println(test2(set));.
Extra challenge:
static int test2(Set<Double> set) {
assert set.isEmpty();
set.add(-0d);
set.add(0d);
set.add(0.0d);
set.add(0.00d);
return set.size();
}
Hint: IEEE 754 can be weird. While 0 is the same as 0.0 and 0.00, you can have negative zero as a different value from positive zero.
Answer: It's two elements ([-0.0, 0.0]).