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

时间:2010-09-03 12:00:48

标签: java list class collections package

程序:

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

输出: 嗳 海 嗨 HW 海

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

3 个答案:

答案 0 :(得分:16)

上面的循环使用索引遍历列表。 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循环(以及泛型):

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

答案 1 :(得分:2)

关键是ac.get(k)不使用iterator的任何元素,而it.next()

答案 2 :(得分:0)

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

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

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