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?