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

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

    iterator object contains the same number of elements what your collection contained.

    List a =...;
    Iterator i = a.iterator();
    int size = a.size();//Because iterators size is equal to list a's size.
    

    But instead of getting the size of iterator and iterating through index 0 to that size, it is better to iterate through the method next() of the iterator.

提交回复
热议问题