javaspliterator

Why does HashSet return -1 for getExactSizeIfKnown


I am trying to understand the features of SplitIterator and came across the below :

public static void main(String[] args) {
    Set<Integer> l = new HashSet();
    l.add(1);
    l.add(2);
    l.add(3);
    Spliterator<Integer> s= (Spliterator<Integer>) l.spliterator();
Spliterator<Integer> s1=s.trySplit();
while(s1.tryAdvance(n -> {System.out.print(n+" ");System.out.println("estimateSize "+s.estimateSize()+" getexactsizeifknown "+s.getExactSizeIfKnown());})); 

Why does the method getexactsizeifknown return -1 for HashSet?

For other collections it returns the same output as the estimateSIze()


Solution

  • The Javadoc describes why:

    Convenience method that returns estimateSize() if this Spliterator is SIZED, else -1.

    So, your spliterator isn't SIZED.