java迭代器,一種模式,可以對(duì)一種數(shù)據(jù)在不清楚其具體內(nèi)部結(jié)構(gòu)(啥類型的數(shù)據(jù))的情況下,可以依次遍歷,取出其中的元素。
方法:boolean hasNext():是否還有元素迭代。 next():返回迭代的下一個(gè)元素。 remove():從迭代器中移除上一次剛添加進(jìn)來的元素。
具體使用: List <String> s=new ArrayList<String>();         s.add("hello");         s.add("world");         Iterator<String> it=s.iterator();         while(it.hasNext()){ System.out.PRintln(it.next());         }
或者用for循環(huán)遍歷取值:
for(Iterator it = s.iterator();it.hasNext();){ String te= (String) it.next();}一些注意點(diǎn): 1.在用迭代器對(duì)集合進(jìn)行操作時(shí),不要進(jìn)行集合的添加,集合的移除等,會(huì)產(chǎn)生異常,如:
while(it.hasNext()){ //s.remove(0);//Exception in thread "main" java.util.ConcurrentModificationException String te= (String) it.next(); System.out.println(te); // s.add("test wrong");//在操作迭代器的同時(shí),操作list集合。Exception in thread "main" java.util.ConcurrentModificationException }2.remove的深刻理解: iterator的remove()方法的前邊必須要有next()方法,先獲得下一個(gè),remove,是將剛才next()讀出的在集合中的給remove掉。可進(jìn)行一個(gè)測(cè)試:
public class Putexercise { public static void main(String[] args) { List <String> s=new ArrayList<String>(); s.add("hello"); s.add("world"); Iterator it=s.iterator(); int flag=0; while(it.hasNext()){ String te= (String) it.next(); if(flag==0){ it.remove(); flag=1; } } System.out.println(s.get(0)); System.out.println(s.get(1));//此時(shí)只能輸出world,報(bào)異常,list的長(zhǎng)度為1. }}Iterator和ListIterator主要區(qū)別在以下方面: 1. ListIterator有add()方法,可以向List中添加對(duì)象,而Iterator不能 2. ListIterator和Iterator都有hasNext()和next()方法,可以實(shí)現(xiàn)順序向后遍歷,但是ListIterator有hasprevious()和previous()方法,可以實(shí)現(xiàn)逆向(順序向前)遍歷。Iterator就不可以。 3. ListIterator可以定位當(dāng)前的索引位置,nextIndex()和previousIndex()可以實(shí)現(xiàn)。Iterator沒有此功能。 4. 都可實(shí)現(xiàn)刪除對(duì)象,但是ListIterator可以實(shí)現(xiàn)對(duì)象的修改,set()方法可以實(shí)現(xiàn)。Iierator僅能遍歷,不能修改。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注