Interator使用方法举例

Interator使用方法,举例

 import java.util.*;
public class TestIterator
{
 public static void main(String[] args)
 {
  //创建一个集合
  Collection books = new HashSet();
  books.add("aaaa");
  books.add("bbbbb");
  books.add("ccccccc");
  //获取books集合对应的迭代器
  Iterator it = books.iterator();
  while(it.hasNext())
  {
   String book = (String)it.next();
   System.out.println(book);
   if (book.equals("bbbbbb"))
   {
    it.remove();
   }
   //对book变量赋值,不会改变集合元素本身
   book = "测试字符串";
  }
  System.out.println("---------------------------");
  System.out.println(books);
 }
}
输出结果:
bbbbb
aaaa
ccccccc
---------------------------
[bbbbb, aaaa, ccccccc]


使用Iterator迭代器注意事项:
在使用迭代器迭代集合的过程中不要修改集合如删除集合元素等,如果修改了集合会发出:
Exception in thread "main" java.util.ConcurrentModificationException
上面的异常信息

iterator吧
List result = new LinkedList();
Iterator it = result.iterator();

http://www.cnblogs.com/chenssy/p/3821328.html