2010-09-03 54 views
3

程序:hasnext()是如何工作的集合中的java

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

輸出: 人工智能 海 喜 HW 海

它如何執行5次? 雖然來到海沒有下一個元素存在,所以條件錯誤。但它是如何執行的。

+1

真正的問題是,如何使用一個Iterator,爲什麼我會收到一個indexOutOfBounds的異常。 – Cid54 2010-09-03 12:08:11

回答

13

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

該點是ac.get(k)不會消耗迭代器的任何相反的元素.next()

0

該循環將永遠不會終止。 it.hasNext不會推進迭代器。你必須調用它.next()來推進它。循環可能會終止,因爲k變成5,在這一點上,Arraylist拋出一個界限異常。

迭代(包含字符串)的列表的正確的形式可以是:

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)); 
}