国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Java > 正文

java迭代器(Iterator)的理解

2019-11-06 08:11:08
字體:
供稿:網(wǎng)友

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僅能遍歷,不能修改。


發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 祥云县| 白城市| 广饶县| 彭山县| 兴安县| 永登县| 东光县| 安泽县| 霍山县| 湘阴县| 攀枝花市| 海门市| 金乡县| 沙洋县| 平度市| 鞍山市| 隆德县| 正安县| 五峰| 五莲县| 芒康县| 伊宁县| 余江县| 绵竹市| 临西县| 石景山区| 漳平市| 衡阳市| 东安县| 利辛县| 丹东市| 绿春县| 庐江县| 酒泉市| 井研县| 贵德县| 阜平县| 赤峰市| 高碑店市| 介休市| 长岭县|