hasnext()如何在java中的集合中工作

程序:

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++; } } } 

输出:ai hai hi hw hai

怎么执行5次?? 虽然来到没有下一个元素存在所以条件错误。 但它是如何执行的。

上面的循环使用索引遍历列表。 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 

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

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

要点是ac.get(k)不会消耗iterator的任何元素,相反it.next()

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

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

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

或者如果列表是类型,例如ArrayList

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

或者,如果你完全知道这是一个数组列表,需要速度超过简洁性:

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