gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 01:04:29 25 4
gpt4 key购买 nike

程序:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com