Nulls

Doug Lea dl at cs.oswego.edu
Fri Sep 21 05:26:07 PDT 2012


On 09/17/12 11:08, Brian Goetz wrote:
> If we'd bitten the bullet and not allowed nulls as elements in Collections from
> the beginning, we'd have less of a problem now.
>
> So, looking at only the sequential case right now, what are the realistic
> options for handling nulls in streams?
>

Here's a stab at helping to clear this up a bit:
Let's separate "dense" and "sparse" aggregates.
A sparse aggregate has some way of representing
and dealing with elements the could be present,
but aren't, by using "null". A dense aggregate only
has elements, not potential elements.

Most sequence/stream-like things are dense,
so null elements make no sense.

Most array/map-like things are sparse -- for example, a null
returned from an indexed or keyed access (a[i] or map.get(key))
means "the index/key is valid, but there's nothing there".

The operations in the current Stream API in general apply only to
actual elements, not representations of potential elements
(i.e., not null).
If you elevate this "in general" to "must", it leads to a choice
of either or both of two simple rules:

1. Stream sources should only present actual elements, not nulls.

2. Stream operations should ignore nulls.

Rule (1) means for example that the stream source for an
ArrayList should not include unoccupied array cells. But the
Iterator that it would be based on in current APIs doesn't do
this filtering. And probably similarly for other classes,
including nonJDK-classes that could not be adjusted to
obey rule (1).

Which, from this line of thinking, pretty much forces rule (2).

There are other lines of thinking that lead to different rules.
Others should feel free to argue for them.

-Doug



More information about the lambda-libs-spec-experts mailing list