Can someone please explain the purpose why do java people override the hascode
in Optional
It allows you to store Optional
s (whose value types also override equals
and hashCode
) in HashSet
s and use them as keys in HashMap
s.
If Optional
didn't override equals
and hashCode
, the following code would output 2
instead of 1
:
Map<Optional<String>,String> map = new HashMap<>();
map.put(Optional.of("someKey"),"someValue");
map.put(Optional.of("someKey"),"someOtherValue");
System.out.println(map.size());