程序:
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/