java迭代器,一种模式,可以对一种数据在不清楚其具体内部结构(啥类型的数据)的情况下,可以依次遍历,取出其中的元素。
方法:boolean hasNext():是否还有元素迭代。 next():返回迭代的下一个元素。 remove():从迭代器中移除上一次刚添加进来的元素。
具体使用: 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循环遍历取值:
for(Iterator it = s.iterator();it.hasNext();){ String te= (String) it.next();}一些注意点: 1.在用迭代器对集合进行操作时,不要进行集合的添加,集合的移除等,会产生异常,如:
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");//在操作迭代器的同时,操作list集合。Exception in thread "main" java.util.ConcurrentModificationException }2.remove的深刻理解: iterator的remove()方法的前边必须要有next()方法,先获得下一个,remove,是将刚才next()读出的在集合中的给remove掉。可进行一个测试:
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));//此时只能输出world,报异常,list的长度为1. }}Iterator和ListIterator主要区别在以下方面: 1. ListIterator有add()方法,可以向List中添加对象,而Iterator不能 2. ListIterator和Iterator都有hasNext()和next()方法,可以实现顺序向后遍历,但是ListIterator有hasprevious()和previous()方法,可以实现逆向(顺序向前)遍历。Iterator就不可以。 3. ListIterator可以定位当前的索引位置,nextIndex()和previousIndex()可以实现。Iterator没有此功能。 4. 都可实现删除对象,但是ListIterator可以实现对象的修改,set()方法可以实现。Iierator仅能遍历,不能修改。
新闻热点
疑难解答