1、创建集合
List <String> list = new ArrayList<>();
//添加数据
list.add("hello");
list.add("world");
list.add("java");
list.add("hello");
list.add("world");
list.add("java");
list.add("hello");
list.add("world");
list.add("java");
普通for循环
for (int i = 0; i <list.size() ; i++) {
list.remove(i);//不能完全的删除集合中的元素
list.set(i,"666"); //成功
list.add(1,"888");//无限循环,无输出结果
list.add("000");//无限循环,无输出结果
System.out.println("------------");
System.out.println(list.get(i));//成功查询
}
增强for循环
for (String s : list) {
//新增
list.add("hahaha");//Exception in thread "main" java.util.ConcurrentModificationException
//修改
list.set(1,"111");//成功
//删除
list.remove(s);//Exception in thread "main" java.util.ConcurrentModificationException
//查询
System.out.println( list.get(2));//成功
}
迭代器
Iterator
java.util.Iterator<String> iterator = list.iterator();
while (iterator.hasNext()){
String next = iterator.next();
iterator.remove();//删除成功
System.out.println(next);//查询成功
}
listIterator
ListIterator<String> stringListIterator = list.listIterator();
while (stringListIterator.hasNext()){
stringListIterator.add("333");//无限循环
stringListIterator.remove();//Exception in thread "main" java.lang.IllegalStateException
System.out.println(stringListIterator.next());//查询成功
}
//输出集合
System.out.println(list);