以前一直都用 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 
蒋家狂潮 阅读(2838) 
评论(12)  编辑  收藏  所属分类: 
Basic