/*
* 集合中的迭代器:
* 获取集合中元素方式
* 接口 Iterator : 两个抽象方法
* boolean hasNext() 判断集合中还有没有可以被取出的元素,如果有返回true
* next() 取出集合中的下一个元素
*
* Iterator接口,找实现类.
* Collection接口定义方法
* Iterator iterator()
* ArrayList 重写方法 iterator(),返回了Iterator接口的实现类的对象
* 使用ArrayList集合的对象
* Iterator it = array.iterator(),运行结果就是Iterator接口的实现类的对象
* it是接口的实现类对象,调用方法 hasNext 和 next 集合元素迭代
*/
public class IteratorDemo {
public static void main(String[] args) {
Collection<String> coll = new ArrayList<String>();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
coll.add("abc4");
//迭代器,对集合ArrayList中的元素进行取出
//调用集合的方法iterator()获取出,Iterator接口的实现类的对象
Iterator<String> it = coll.iterator();
//接口实现类对象,调用方法hasNext()判断集合中是否有元素
//boolean b = it.hasNext();
//System.out.println(b); true
//接口的实现类对象,调用方法next()取出集合中的元素
//String s = it.next();
//System.out.println(s);
//迭代是反复内容,使用循环实现,循环的条件,集合中没元素, hasNext()返回了false
while(it.hasNext()){
String s = it.next();
System.out.println(s);
}
/*for (Iterator<String> it2 = coll.iterator(); it2.hasNext(); ) {
System.out.println(it2.next());
}*/
}
}
运行结果:abc1 abc2 abc3 abc4
迭代器中的转型:
public class CollectionDemo1 {
public static void main(String[] args) {
//集合可以存储任意类型的对象
//集合中,不指定存储的数据类型, 集合什么都存
Collection coll = new ArrayList();
coll.add("abc");
coll.add("uyjgtfd");
//迭代器获取
Iterator it = coll.iterator();
while(it.hasNext()){
//it.next()获取出来的是什么数据类型,Object类
//Object obj = it.next();
//System.out.println(obj); abc uyjgtfd
//强转有风险,如果集合中存在非String类型的数据,则会出现类型转换异常
String s = (String)it.next();
System.out.println(s.length());
}
}
}
运行结果:3 7
并发修改异常:
出现原因:
迭代器遍历的过程中,通过集合对象修改了集合中的元素,造成了迭代器获取元素中判断预期修改值和实际 修改值不一致,则会出现:ConcurrentModificationException
解决方案:
用for循环遍历,然后用集合对象做对应的操作即可
public class ListDemo { public static void main(String[] args) { //创建集合对象 List<String> list = new ArrayList<>(); //添加元素 list.add("hello"); list.add("world"); list.add("java"); /* 利用迭代器遍历集合,判断集合中是否有“world”这个元素, 如果有就添加一个“javaee”元素 */ Iterator<String> it = list.iterator(); while (it.hasNext()){ String s = it.next(); if(s.equals("world")){ list.add("javaee"); } }
for (int i = 0; i < list.size(); i++) {
String s = list.get(i);
if(s.equals("world")){
list.add("javaee");
}
}
} }
运行结果:
列表迭代器
ListIterator介绍 :
通过List集合的listIterator()方法得到,所以说它是List集合特有的迭代器
用于允许程序员沿任一方向遍历的列表迭代器,在迭代期间修改列表,并获取列表中迭代器的当前位置 示例代码
public class ListIteratorDemo { public static void main(String[] args) { //创建集合对象 List<String> list = new ArrayList<>(); //添加元素 list.add("abc"); list.add("java"); list.add("lol"); //获取列表迭代器 ListIterator<String> lit = list.listIterator(); while (lit.hasNext()){ String s = lit.next(); if(s.equals("java")){ lit.add("haha"); } } System.out.println(list); } }
运行结果: