首页 > 代码库 > Java复习之-Iterator

Java复习之-Iterator

Iterator和collection和map系列不一样,后两个主要是用来装入其他对象,Iterator主要是用来遍历collection中的对象,Iterator也被称为迭代器,

Iterator必须依附于collection对象

package Mypackage;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

import Myproject.interface_my;

 

public class Mycollection {
public static void main(String[] args){
Collection collection=new ArrayList();
collection.add("lee");
collection.add("love you");
System.out.println(collection.size());
System.out.println(collection.contains(7));
collection.add("这是一个美丽的早晨");
System.out.println(collection);
System.out.println(collection.toString());
System.out.println(collection.toArray()[1]);
Collection booksCollection=new HashSet();
booksCollection.add("Java");
booksCollection.add("php");
System.out.println(booksCollection);
booksCollection.clear();
Iterator it=collection.iterator();
while(it.hasNext()){
String books=(String)it.next();
if(books.equals("lee")){
//使用Iterator对象过程中不能修改集合元素,否则会出现异常
collection.remove(books);
}
System.out.println("shuo:"+books);
}

}
}

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at Mypackage.Mycollection.main(Mycollection.java:30)

Iterator采用的是快速失败机制,一旦检测到集合被修改,马上抛出ConcurrentModificationException异常。

for(Object object:collection){
String dataString=(String)object;
System.out.println(dataString);
}

foreach循环过程中也不能修改collection集合,不然一样报ConcurrentModificationException错。

Java复习之-Iterator