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

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

    There is no more efficient way, if all you have is the iterator. And if the iterator can only be used once, then getting the count before you get the iterator's contents is ... problematic.

    The solution is either to change your application so that it doesn't need the count, or to obtain the count by some other means. (For example, pass a Collection rather than Iterator ...)

提交回复
热议问题