Infinite loop while using iterator

前端 未结 4 1262
我在风中等你
我在风中等你 2021-01-29 11:45
Set key1 = map.keySet();
Iterator it1 = key1.iterator();
int cnt=0;
while (it1.hasNext()) {
  cnt++;
}

What are the chances that this code will result

相关标签:
4条回答
  • 2021-01-29 12:06

    Basically itl.hasNext() always return a boolean value based on the availability of next value to process in the collection. Say pointer is at some position x, hasNext() returns true if there exists some element next to position x, i mean x+1 element exists,

    So you must use itl.next(), which returns the current element in the collection and moves the pointer ahead by 1. so according to our previous example, next() returns current object a position x, and moves the pointer to next poiton.

    However to get the number of elements from a collection you could use

     collection_object.size()
    
    0 讨论(0)
  • 2021-01-29 12:09

    Actually it is resulting in infinite loop. My doubt is it is because I am not taking it1.next(); , is it true?

    Yes, this is true.

    However, you can find the count of a collection much easier:

    int cnt = map.size();
    
    0 讨论(0)
  • 2021-01-29 12:13

    The problem is, that you don't call it1.next() in the loop, so it1.hasNext() is always true. In other words, you never move to the next item.

    BTW, you don't need iterator for what you want to archieve, try

    int cnt=map.size();
    
    0 讨论(0)
  • 2021-01-29 12:17

    Yes. Until you don't call it1.next() it will never move on to next item. Beause it1.next() will return the object which you have added in the list/set.

    0 讨论(0)
提交回复
热议问题