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

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

输出: 艾 海 你好 硬件 嗨

它如何执行 5 次? 而 come to hai 没有下一个元素存在,所以条件为 false。但是它是如何执行的。

最佳答案

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

关于java - hasnext() 如何在 Java 中的集合中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3635474/

相关文章:

java - 如何使用 java 从 hdfs 读取多个文件?

list - 将列表值 append 到字典中

python - 根据类 python 2.7 中的变量按字母顺序对类列表进行排序

java - Lucene 的 Ruby 替代品

java - 将 double[][] 转换为 float[][]

java - IzPack 可执行文件不适用于 linux 脚本

python - 如何用Python中字典中的键替换列表中的项目

python - 按长度对列表列表进行排序时跟踪原始索引

php - 在我的类(class)文件中出现错误 “Unexpected $end”

c# - 我如何通过 C# 中的函数动态获取属性?