EnumSet.spliterator without characteristic Spliterator.NONNULL

LuCio :

I was thinking about an answer to the question: How to test for null keys on any Java map implementation?

My first thought was to check if the Spliterator of the keyset of a map has the characteristic Spliterator.NONNULL:

map.keySet().spliterator().hasCharacteristics(Spliterator.NONNULL)

The JavaDoc says:

Characteristic value signifying that the source guarantees that encountered elements will not be null. (This applies, for example, to most concurrent collections, queues, and maps.)

Before answering I did some checks:

The Spliterator of aTreeMap without a provided Compararator does not have this characteristic even though the natural ordering does not allow null-keys.

new TreeMap<>().keySet().spliterator().hasCharacteristics(Spliterator.NONNULL); // false 

Even more suprising was the fact that Spliterators of an EnumMap keyset and of EnumSet itself do not have this characteristic.

EnumSet.allOf(DayOfWeek.class).spliterator().hasCharacteristics(Spliterator.NONNULL); // false

I understand that the result of spliterator().hasCharacteristics(Spliterator.NONNULL) in the above cases returns false as the default implementation of Set.spliterator() is evaluated.

But is there a reason why the spliterators of these sets do not override Set.spliterator() to create a Spliterator with Spliterator.NONNULL? Would this break a specification I am not aware of?

Eugene :

Even worse:

System.out.println(Set.of(1)
             .spliterator()
             .hasCharacteristics(Spliterator.NONNULL)); // false

Even if those Set::of methods are documented as:

throws NullPointerException if the element is null

So there is no way to end up with a null in that Set. I guess the real answer is that this is not yet done.

EDIT

See the comment from Stuart Marks about this

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=74832&siteId=1