What is the best way to get the count/length/size of an iterator?

后端 未结 9 1113
青春惊慌失措
青春惊慌失措 2020-12-03 00:01

Is there a \"computationally\" quick way to get the count of an iterator?

int i = 0;
for ( ; some_iterator.hasNext() ; ++i ) some_iterator.next();

9条回答
  •  我在风中等你
    2020-12-03 00:53

    If all you have is the iterator, then no, there is no "better" way. If the iterator comes from a collection you could as that for size.

    Keep in mind that Iterator is just an interface for traversing distinct values, you would very well have code such as this

        new Iterator() {
            final Random r = new Random();
            @Override
            public boolean hasNext() {
                return true;
            }
    
            @Override
            public Long next() {
                return r.nextLong();
            }
    
            @Override
            public void remove() {
                throw new IllegalArgumentException("Not implemented");
            }
        };
    

    or

        new Iterator() {
            BigInteger next = BigInteger.ZERO;
    
            @Override
            public boolean hasNext() {
                return true;
            }
    
            @Override
            public BigInteger next() {
                BigInteger current = next;
                next = next.add(BigInteger.ONE);
                return current;
            }
    
            @Override
            public void remove() {
                throw new IllegalArgumentException("Not implemented");
            }
        }; 
    

提交回复
热议问题