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

后端 未结 9 1095
青春惊慌失措
青春惊慌失措 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 01:00

    Your code will give you an exception when you reach the end of the iterator. You could do:

    int i = 0;
    while(iterator.hasNext()) {
        i++;
        iterator.next();
    }
    

    If you had access to the underlying collection, you would be able to call coll.size()...

    EDIT OK you have amended...

提交回复
热议问题