??????? 以前一直都用 Iterator,一直沒出現問題,后來當我將 Iterator 作為一個方法的參數傳進去,當Iterator 執行循環兩次的時候問題出現了,第一次可以執行,而第二次卻輸出不了值了;經過同事提醒,原來 Iterator? 執行循環的時候,一次執行就到達最后的節點,若再循環一次,自然不能再從頭開始。那么有什么辦法執行兩次或兩次以上呢,解決的辦法就是再重新生成一個新的Iterator對象。 我做了一個試驗,如下:
import java.util.ArrayList;
import java.util.Iterator;
public class TestIterator {
?? public? TestIterator(){
??? ArrayList list=new ArrayList();
??? Integer in;
??? for(int i=0;i<5;i++){
???? in=new Integer(i+10);
???? list.add(in);
??? }
??? Iterator it=list.iterator();
??? System.out.println("(1) first time to loop.....");
??? System.out.println("the (1) result is.....");
??? while(it.hasNext()){
???? Integer i=(Integer)it.next();
???? System.out.println("(1)The value is:"+i);
??? }
??? System.out.println();
??? System.out.println("(2) second time to loop.....");
??? System.out.println("the (2) result is.....");
??? while(it.hasNext()){
???? Integer i=(Integer)it.next();
???? System.out.println("(2)The value is:"+i);
??? }
??? System.out.println();
??? System.out.println("(3) third time to loop.....");
??? System.out.println("when this iterator is new one...");
??? System.out.println("the (3) result is.....");
??? it=list.iterator();
??? while(it.hasNext()){
???? Integer i=(Integer)it.next();
???? System.out.println("(3)The value is:"+i);
??? }
?? }
?? public static void main(String args[]){
????? new? TestIterator();
?? }
}
輸出的結果:
(1) first time to loop.....
the (1) result is.....
(1)The value is:10
(1)The value is:11
(1)The value is:12
(1)The value is:13
(1)The value is:14
(2) second time to loop.....
the (2) result is.....
(3) third time to loop.....
when this iterator is new one...
the (3) result is.....
(3)The value is:10
(3)The value is:11
(3)The value is:12
(3)The value is:13
(3)The value is:14
可以看出,它根本不執行第(2)個循環,當重新生成一個新的Iterator對象,第(3)個方法就能輸出循環了。
posted on 2007-09-20 11:52
蔣家狂潮 閱讀(2804)
評論(12) 編輯 收藏 所屬分類:
Basic