how hasnext() works in collection in java

后端 未结 3 1936
囚心锁ツ
囚心锁ツ 2021-02-10 14:10

program:

public class SortedSet1 {

  public static void main(String[] args) {  

    List ac= new ArrayList();

    c.add(ac);
    ac.add(0,\"hai\");
    ac.add         


        
3条回答
  •  [愿得一人]
    2021-02-10 14:32

    Your loop above iterates through the list using an index. it.hasNext() returns true until it reaches the end of the list. Since you don't call it.next() within your loop to advance the iterator, it.hasNext() keeps returning true, and your loop rolls on. Until, that is, k gets to be 5, at which point an IndexOutOfBoundsException is thrown, which exits the loop.

    The proper idiom using an iterator would be

    while(it.hasNext()){
        System.out.println(it.next());
    }
    

    or using an index

    for(int k=0; k

    However since Java5, the preferred way is using the foreach loop (and generics):

    List ac= new ArrayList();
    ...
    for(String elem : ac){
        System.out.println(elem);
    }
    

提交回复
热议问题