您的代碼會錯過一些重要的事情,但你要做的第一件事是,要麼投用Iterator.next()調用的返回值(在你的代碼失蹤)或使用泛型讓編譯器爲你整理它。
的兩個備選方案會是這個樣子(沒有嘗試編譯他們,但他們應該是基本上是正確的):
隨着投:
ArrayList array = new ArrayList();
...
Iterator it1 = array.iterator();
while (it1.hasNext()){
Myclass temp = (Myclass)it1.next()
System.out.println (temp);
}
有了泛型:
ArrayList<Myclass> array = new ArrayList<Myclass>();
...
Iterator<Myclass> it1 = array.iterator();
while (it1.hasNext()){
Myclass temp = it1.next()
System.out.println (temp);
}
編輯:正如其他人指出的那樣,在大多數情況下使用foreach構造更適合可讀性。我決定只是儘可能少地修改你的初始代碼。 A for構造看起來是這樣的:
ArrayList<Myclass> array = new ArrayList<Myclass>();
...
for(Myclass temp : array){
System.out.println (temp);
}
您需要將'Iterator'泛化到'Iterator',否?或者直接到'for(MyClass c in array)'。 –
2010-02-19 22:08:17
@Michael Brewer-Davis:它會自動爲您完成,具有泛型的集合將返回相應的迭代器。它需要被正確地聲明。 – Fredrik 2010-02-19 22:12:04
@curlingdude:現在當你的答案被接受時,也許你應該考慮糾正它?您混合使用「MyClass」和「Myclass」,它在「Iterator it1」聲明中完全省略。 – Fredrik 2010-02-19 22:19:54