【问题标题】:how hasnext() works in collection in javahasext() 如何在 java 中的集合中工作
【发布时间】:2011-04-07 19:42:05
【问题描述】:

程序:

public class SortedSet1 {

  public static void main(String[] args) {  

    List ac= new ArrayList();

    c.add(ac);
    ac.add(0,"hai");
    ac.add(1,"hw");
    ac.add(2,"ai"); 
    ac.add(3,"hi"); 
    ac.add("hai");

    Collections.sort(ac);

    Iterator it=ac.iterator();

    k=0;

    while(it.hasNext()) {    
      System.out.println(""+ac.get(k));
      k++;     
    }
  }
}

输出: 艾 海 你好 硬件 喂

它如何执行 5 次? 虽然来到 hai 没有下一个元素存在,所以条件为假。但它是如何执行的。

【问题讨论】:

  • 真正的问题是,如何使用迭代器以及为什么会出现 indexOutOfBounds 异常。

标签: java list class collections package


【解决方案1】:

上面的循环使用索引遍历列表。 it.hasNext() 返回 true,直到 it 到达列表末尾。由于您没有在循环中调用 it.next() 来推进迭代器,因此 it.hasNext() 会一直返回 true,并且您的循环继续进行。直到,即k 变为 5,此时抛出 IndexOutOfBoundsException,退出循环。

使用迭代器的正确习惯用法是

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

或使用索引

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

然而,从 Java5 开始,首选的方法是使用 foreach 循环(和 generics):

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

【讨论】:

    【解决方案2】:

    关键是 ac.get(k) 不消耗迭代器的任何元素,相反 it.next()

    【讨论】:

      【解决方案3】:

      那个循环永远不会终止。 it.hasNext 不推进迭代器。你必须调用 it.next() 来推进它。循环可能会终止,因为 k 变为 5,此时 Arraylist 会抛出边界异常。

      迭代列表(包含字符串)的正确形式是:

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

      或者如果输入了列表,例如数组列表

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

      或者,如果您绝对知道这是一个数组列表并且需要速度而不是简洁:

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

      【讨论】:

        猜你喜欢
        • 2015-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-20
        • 1970-01-01
        • 2011-10-07
        • 1970-01-01
        • 2011-02-01
        相关资源
        最近更新 更多