Optional Class : equals, hashCode and toString methods with examples

1. Overview

In this article, we will look at 3 different methods of Optional class which are overridden from Object class. As you would have guessed these methods are equals, hashCode and toString.

This article is part of ongoing series of Optional. Read about it more here.

2. equals(Object obj)

equals method is used to test whether the Optional object specified in parameter is equal to this Optional. equals method returns true if both instances are empty or both Optional has the same value.

Empty Optional Test :

Optional<String> optString = Optional.empty();
Assert.assertTrue(optString.equals(Optional.empty()));

Optional with value :

Optional<String> optString = Optional.of("abc");
Assert.assertTrue(optString.equals(Optional.of("abc")));

3. hashCode()

hashCode method is used to generate the hash code for Optional object whose value is present. If value is absent then 0(zero) is returned.

Empty Optional :

Optional<String> optString = Optional.empty();
Assert.assertEquals(0, optString.hashCode());

Optional with value :

int hashCode = Optional.of("abc").hashCode();
Assert.assertTrue(hashCode != 0);

4. toString()

toString method is used to convert the Optional object to string. 

Empty Optional :

Optional<String> optString = Optional.empty();
Assert.assertEquals("Optional.empty", optString.toString());

Optional with value :

Optional<String> optString = Optional.of("abc");
Assert.assertEquals("Optional[abc]", optString.toString());

6. Conclusion

In this article, we discussed 3 methods that are inherited by Optional class from Object class i.e. equals, hashCode and toString.

Leave a Reply

Your email address will not be published. Required fields are marked *