Search code examples
javajava-8option-typehashcodeapi-design

What is the purpose of having hashCode in Optional


Can someone please explain the purpose why do java people override the hascode in Optional


Solution

  • It allows you to store Optionals (whose value types also override equals and hashCode) in HashSets and use them as keys in HashMaps.

    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());