程序:
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++;
}
}
}输出: ai hai hi hw hai
它如何执行5次??而到了海边,没有下一个元素出现,所以条件不正确。但它是如何执行的。
发布于 2010-09-03 20:02:53
上面的循环使用索引遍历列表。在it到达列表末尾之前,it.hasNext()将返回true。因为您没有在循环中调用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);
}发布于 2010-09-03 20:04:42
关键是与it.next()相反,ac.get(k)不消耗迭代器的任何元素。
发布于 2010-09-03 20:32:41
那个循环永远不会结束。it.hasNext不推进迭代器。您必须调用it.next()来推进它。循环可能会终止,因为k变为5,此时数组抛出边界异常。
迭代列表(包含字符串)的正确形式是:
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));
}https://stackoverflow.com/questions/3635474
复制相似问题