java.util.Optional fields

Peter Levart peter.levart at gmail.com
Fri Sep 21 04:41:30 PDT 2012


Maybe the intention was to allow null values to be wrapped in non-empty 
Optional? In that case the check for non-null in constructor is wrong...

Regards, Peter

On 09/21/2012 01:35 PM, Peter Levart wrote:
> Hi all,
>
> I'm just thinking about the implementation of current java.util.Optional.
>
> It has 2 fields: "T value" and "boolean present".
>
> But since the invariant is:
>
>     public Optional(T value) {
>         this.value = Objects.requireNonNull(value);
>         this.present = true;
>     }
>
>     private Optional() {
>         this.value = null;
>         this.present = false;
>     }
>
> // value != null && present || value == null && !present.
>
> Isn't the "present" flag superfluous? Or is this intentional? Is the 
> test for boolean faster that the check for reference equality with 
> null? Does additional boolean flag, considering alignment constraints, 
> produce a larger object or does it not?
>
> Regards, Peter
>



More information about the lambda-dev mailing list