-1

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

Mehraj Malik
  • 14,872
  • 15
  • 58
  • 85
  • 2
    What do you mean by "java people override the `hashCode` in `Optional`"? Normally there's no reason to do that (it's already implemented in a useful way). – T.J. Crowder Aug 16 '18 at 10:23
  • For the same reason as the `hashCode` in `String` and other value-classes :) – Alex Shesterov Aug 16 '18 at 10:23
  • 2
    Overriding `hashCode` in `Optional` enables sensible use of `HashSet/Map` with `Optional` entries respectively keys. Without the override, it would be the system hash of the `Optional` object. The override uses the hash of the underlying object. And above all: `equals` and `hashCode` have to be consistent! equals(a,b) == true => hashCode(a) == hashCode(b) Ergo: If you override `equals` (is done in `Optional` to make two instances having equals underlying objects the same), you also have to override `hashCode` in a consistent manner. – jokster Aug 16 '18 at 10:28

2 Answers2

5

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());
Eran
  • 387,369
  • 54
  • 702
  • 768
0

From JavaDoc:

Returns the hash code value of the present value, if any, or 0 (zero) if no value is present.

So you can check if objects inside Optional is equals to each others. It also correspond well with implementation of equals method.

rechandler
  • 756
  • 8
  • 22