1. 程式人生 > >Iterator和ListIterator的知識點

Iterator和ListIterator的知識點

      又有好多天沒有寫部落格,也就意味著好多天沒有進行常規的學習Java了,這些天忙著申請獎的事情,發現自己心態還是不好,因為那件事好幾天沒能睡好,好幾天沒能按正常步驟做事~不過好在有個好的結果。這是對自己以前工作態度的肯定,同時也是鼓勵自己更加努力的學習。好了,現在開始學習技術~

      首次接觸到Iterator是在看到集合的程式的時候,那時候使用Iterator來讀取集合中的元素,開始一直是讀取,簡單程式碼如下:

public class IteratorDemo {

	/**
	 * @param args
	 * 
	 * Iterator iterator 取出元素的方式,
	 * 該物件必須依賴於具體的容器,因為每一個容器的資料結構都不同。
	 * 所以該迭代器物件是在容器中進行內部實現的
	 * 對於具體容器而言,具體的實現不重要,只要通過容器獲取該實現的迭代器的物件即可。
	 * 
	 * Iterator藉口就是對所有Collection容器進行元素取出的公共介面。
	 * 
	 */
	public static void main(String[] args) {
		//
		Collection coll=new ArrayList();
		
		coll.add("linweieran1");
		coll.add("linweieran2");
		coll.add("linweieran3");
		coll.add("linweieran4");
		coll.add("linweieran5");
		 
		//使用Collecion中的iterator方法。是為了獲取集合中的物件
		/*
		Iterator it=coll.iterator();  這樣子雖然可以用,但while迴圈結束後it還保留在記憶體中,不好
		while(it.hasNext()){
			System.out.println(it.next());
		}
		*/
		
		//所以使用for迴圈比較好。
		for(Iterator it=coll.iterator();it.hasNext();){
			System.out.println(it.next());
		}
		
		//Collection coll=new List();
		
		System.out.println(coll);
		
		
	}
就像在程式中寫道的那樣Iterator iterator 取出元素的方式,
* 該物件必須依賴於具體的容器,因為每一個容器的資料結構都不同。
* 所以該迭代器物件是在容器中進行內部實現的
* 對於具體容器而言,具體的實現不重要,只要通過容器獲取該實現的迭代器的物件即可。
* Iterator介面就是對所有Collection容器進行元素取出的公共介面。

但是在執行另一個程式碼的時候,就出現了問題。程式碼如下:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		List list=new ArrayList();
		//show(list);
		
		list.add("abc");
		list.add("abc1");
		list.add("abc2");
		
		Iterator it=list.iterator();
		while(it.hasNext()){
			Object obj=it.next();  //java.util.ConcurrentModificationException
			//如果集合中有abc2那麼就在連結串列中新增abc9
			if(obj.equals("abc2")){
				 list.add("abc9");
			}
			else
				System.out.println("next:"+obj);
		}
這個小小程式的作用就是當集合中有abc2的時候就在集合中新增abc9。當在執行的時候回出現錯誤提示:



出現了

java.util.ConcurrentModificationException的錯誤提示。

這個提示的意思就是:當方法檢測到物件的併發修改,但不允許這種修改時,丟擲此異常。

      在這個程式中,在迭代過程中向集合中增加元素,迭代和集合同時執行,所以出現此異常。這是迭代器本身就侷限性,所以在迭代過程中不使用集合操作,容易出現異常。用一種方法就可以解決此問題,有一個已知的子介面ListIterator();使用Iterator介面的子介面,ListIterator來進行操作,他可以實現在迭代過程中對元素的增刪改查,注意只有list集合具有該迭代功能,程式碼如下:

public static void main(String[] args) {
		// TODO Auto-generated method stub
		List list=new ArrayList();
		//show(list);
		
		list.add("abc");
		list.add("abc1");
		list.add("abc2");
		
		ListIterator it=list.listIterator();
		while(it.hasNext()){
			Object obj=it.next();  //java.util.ConcurrentModificationException
			
			if(obj.equals("abc2")){
				 it.add("abc9");
			}
			else
				System.out.println("next:"+obj);
		}
		System.out.println(list);
		
	}

	public static void show(List list) {
		// TODO Auto-generated method stub
		list.add("abc1");
		list.add("abc2");
		list.add("abc3");
		
		Iterator it=list.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
		
	}

執行結果正常。哈哈