how hasnext() works in collection in java

后端 未结 3 1942
囚心锁ツ
囚心锁ツ 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:40

    That loop will never terminate. it.hasNext does not advance the iterator. You have to call it.next() to advance it. The loop probably terminates because k becomes 5 at which point the Arraylist with throw a bounds exception.

    The correct form of iterating a list (containing strings) is either:

    Iterator it = ac.iterator();
    while (it.hasNext) {
      System.out.println((String) it.next());
    }
    

    Or if the list is typed, e.g. ArrayList

    for (String s : ac) {
      System.out.println((String) s);
    }
    

    Or if you absolutely know this is an array list and need speed over terseness:

    for (int i = 0; i < ac.size(); i++) {
      System.out.println(ac.get(i));
    }
    

提交回复
热议问题