简体   繁体   中英

Why does Spliterator<?> defines NONNULL as a characteristic?

The javadoc of Spliterator (which is basically what is really behind a Stream if I understand things correctly) defines many characeristics which make sense such as SIZED , CONCURRENT , IMMUTABLE etc.

But it also defines NONNULL ; why?

I'd have though that it would be the user's responsibility to ensure that and that if, for instance, a developer tried to .sort() a non SORTED stream where there are null elements he/she would rightfully be greeted with an NPE...

But then this characteristic exists. Why? The javadoc of Spliterator itself doesn't mention any real usage of it, and neither does the package-info.java of the java.util.stream package...

From the documentation of Spliterator :

A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED , DISTINCT , SORTED , SIZED , NONNULL , IMMUTABLE , CONCURRENT , and SUBSIZED . These may be employed by Spliterator clients to control, specialize or simplify computation.

Note that it does not mention the prevention of NullPointerException s. If you sort a Stream which might contain null values it is your responsibility to provide a Comparator which can handle null s.

The second sentence also makes it clear that using these flags is only an option, not a requirement for “Spliterator clients”, which is not limited to usage by Stream s.


So regardless of whether it is used by the current implementation of the Stream API, are there possibilities to gain advantage of the knowledge about a NONULL characteristic?

I think so. An implementation may branch to a specialized code for a non- null Spliterator to utilize null for representing certain state then, eg absent values or the initial value before processing the first element, etc. If fact, the actual implementation code for dealing with Stream s which may contain null is complicated. But of course, you always have to weigh up whether the simplification of one case justifies the code duplication.

But sometimes the simplification is as simple as knowing that there are no null values implies that you can use one of the Concurrent… Collections, which don't allow null s, internally.

I found the following comments in the code for the enum StreamOpFlag .

// The following Spliterator characteristics are not currently used but a
// gap in the bit set is deliberately retained to enable corresponding
// stream flags if//when required without modification to other flag values.
//
// 4, 0x00000100 NONNULL(4, ...
// 5, 0x00000400 IMMUTABLE(5, ...
// 6, 0x00001000 CONCURRENT(6, ...
// 7, 0x00004000 SUBSIZED(7, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM