import java.util.*;
public class CollectionEach {
public static void main(String[] args) {
Collection books = new HashSet();
books.add("书1");
books.add("书2");
books.add("书3");
books.add("书4");
Iterator it = books.iterator();
while(it.hasNext()) {
String book = (String)it.next();
System.out.println(book);
if (book == "书3") {
System.out.println("出现书3,删除");
it.remove();
}
if (book == "书2") {
System.out.println("出现书2,删除");
books.remove(book);
// 出现ConcurrentModificationException异常,
//使用Iterator迭代过程中,集合元素不能被改变,只有通过Iterator的remove()方法删除才可以
}
}
System.out.println(books);
}
}
编译运行结果: