Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the purpose of the OptionalInt.isPresent field?

Tags:

java

Looking at the source code for java.util.OptionalInt, an optional int is made of an int value and a boolean isPresent. The only way of obtaining an empty optional int is through the OptionalInt.empty() method which returns OptionalInt.EMPTY, the common instance for all empty optional ints.

If this is the case, then why is the isPresent() method implemented as return isPresent rather than this == EMPTY and reducing memory usage by getting rid of the isPresent field?

like image 252
Stefan Avatar asked Sep 10 '18 00:09

Stefan


People also ask

What is an OptionalInt?

In Java, an OptionalInt object is a container object that may or may not contain an integer value. The OptionalInt class is present in the java. util package. The getAsInt() method is used to get the integer value present in an OptionalInt object.

What is optional in Java?

Optional is a container object used to contain not-null objects. Optional object is used to represent null with absent value. This class has various utility methods to facilitate code to handle values as 'available' or 'not available' instead of checking null values.


1 Answers

It's an implementation choice and the only people who can give a clear answer are the people who wrote the implementation.

But very likely it's a choice that puts readability, clarity and maintainability of code over memory micro optimizations.

It really doesn't make much sense to be worried about the space a boolean takes up in an object that wraps an int. If that space is relevant, an OptionalInt shouldn't be used in the first place, (or Java for that matter,) considering the object header needs at least 8 bytes (on 32 bit JVMs, more on 64 bit) already.

Java isn't for writing memory constrained applications, it's for writing easily maintainable code. And implementing isPresent() as getter for isPresent is easier to read, less error prone when refactoring and fits with established Java coding practices.

On a side note: Since Java objects are 8 byte aligned it probably doesn't even make the class smaller when you remove isPresent. As Eugene pointed out in a comment, it actually does increase the size, as the field isPresent lies right on the boundary and then 7 more bytes are added for padding.

like image 152
Max Vollmer Avatar answered Oct 10 '22 21:10

Max Vollmer