Why Iterators.size() making the iterator empty?

  • A+
public static void main(String args[]) throws JSONException {     JSONObject json = new JSONObject();     json.put("name", "abcgdj");     json.put("no", "1234");     json.put("contact", "6748356");     Iterator<?> keys = json.keys();     System.err.println(Iterators.size(keys));     System.err.println(Iterators.size(keys)); } 

In this code, after executing Iterators.size(keys), the iterator is becoming empty and for the second print statement, it returning 0.

The size() method is under the package com.google.common.collect.iterators.So I've looked the code of Iterators.size() function.It was,

 public static int size(Iterator<?> iterator) {     long count = 0L;     while (iterator.hasNext()) {     iterator.next();     count++;   }   return Ints.saturatedCast(count); } 

So I have a doubt that how the iterator keys becomes empty. whether it is called by reference?

Can anyone explain what's happening inside size() function



As it says in the Javadoc, this exhausts the keys iterator: it just keeps calling next() until hasNext() is false.

Then it's not reset before you call


again (because there's no way to reset an iterator). So hasNext() immediately returns false, so there are no more elements for it to read. Hence the size is zero.

You'd need to reassign the variable with a new iterator:

Iterator<?> keys = json.keys(); System.err.println(Iterators.size(keys));  keys = json.keys();  //  System.err.println(Iterators.size(keys)); 

or don't declare a variable (since it's effectively (*) useless afterwards):

System.err.println(Iterators.size(json.keys())); System.err.println(Iterators.size(json.keys()));     

(*) You could use it to remove the last element of the iterator.


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: