Vin*_*mar 4 java collections class list 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++;
}
}
}
Run Code Online (Sandbox Code Playgroud)
输出:ai hai hi hw hai
它如何执行5次?虽然来到海没有下一个元素存在所以条件错误.但它是如何执行的.
Pét*_*rök 16
上面的循环使用索引遍历列表.it.hasNext()返回true直到it到达列表的末尾.由于您没有it.next()在循环内调用以推进迭代器,因此it.hasNext()保持返回true,并且循环继续.直到,即,k变为5,此时IndexOutOfBoundsException抛出a,退出循环.
使用迭代器的正确习惯是
while(it.hasNext()){
System.out.println(it.next());
}
Run Code Online (Sandbox Code Playgroud)
或使用索引
for(int k=0; k<ac.size(); k++) {
System.out.println(ac.get(k));
}
Run Code Online (Sandbox Code Playgroud)
但是从Java5开始,首选的方法是使用foreach循环(和泛型):
List<String> ac= new ArrayList<String>();
...
for(String elem : ac){
System.out.println(elem);
}
Run Code Online (Sandbox Code Playgroud)