如何在Java集合中工作

如何在Java集合中工作

本文介绍了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++;
    }
  }
}

输出:ihai你好w

output:aihaihihwhai

它如何执行5次?到hai时,没有下一个元素存在,因此条件为false.但是它是如何执行的.

how it execute 5 times??while come to hai no next element present so condition false. But how it executed.

推荐答案

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

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

或使用索引

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

但是,自Java5以来,首选方式是使用 foreach循环(和泛型):

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

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

这篇关于hasnext()如何在Java集合中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 15:31