Optional hashCode() method in Java with examples
For determining the hashCode value of this Optional instance in Java, implement the hashCode() method of the java.util.Optional class. In the circumstance that this Optional instance is empty, this function returns 0.
HashCode() must always return the same value when called on the same object more than once while a Java program is running, assuming that the data used to compare the object's equals is not changed.
Syntax:
public int hashCode()
Parameter: There are no parameters accepted by this method.
Return Value: This method returns the hashCode value of this Optional instance. If it contains no values, it returns 0.
Exception: There are no exceptions thrown by this method.
The below are the two different examples of the hashCode()method.
Example 1: If Value is Present
The implementation of {Optional} to wrap an integer value is demonstrated in this Java function. It uses the value that is provided to initialize a 'Optional' object. The {Optional} value and hash code are then printed. However, calling hashCode() directly on an 'Optional' object could not get the desired outcome since it returns the enclosed object's hash code instead of the Optional itself.
Implementation:
FileName: OptionalHashCodeValue.java
import java.io.*; import java.util.*; public class OptionalHashCodeValue { public static void main(String[] args) { Optionalo = Optional.of(10455); System.out.println("The Optional value: " + o); System.out.println("The Optional hashCode value is: " + o.hashCode()); } }
Output:
The Optional value: Optional[10455] The Optional hashCode value is: 10455
Example 2: If No Value is Present
The following snippet of Java code shows how to use Optional with no value by using Optional.empty(). An empty Optional object is initialized and then printed. It aims to print the Optional's hash code, just like the preceding example performed. HashCode() produces the same hash code for all empty Optional instances; therefore, if we call it an empty Optional, we might not get any useful information because there is no value present.
Implementation:
FileName: OptionalHashcodeNoValue.java
import java.io.*; import java.util.*; public class OptionalHashcodeNoValue { public static void main(String[] args) { Optionalo = Optional.empty(); System.out.println("The Optional is: " + o); System.out.println("The Optional hashCode value is: " + o.hashCode()); } }
Output:
The Optional is: Optional.empty The Optional hashCode value is: 0