- iterator迭代器遍历
迭代器是集合特有的遍历方式
但是遍历的同时是不能进行添加的Student student = new Student("19","zx"); Student zzx = new Student("20", "zzx"); Student zzz = new Student("21", "zzz"); List<Student> list = new ArrayList<>(); list.add(student); list.add(zzx); list.add(zzz); Iterator<Student> iterator = list.iterator(); while (iterator.hasNext()){ Student s=iterator.next(); System.out.println(s.getName()+" "+s.getAge()); }
while (iterator.hasNext()){ Student s=iterator.next(); if (s.getName().equals("zx")){ list.add(student); } System.out.println(s.getName()+" "+s.getAge()); }
会出现ConcurrentModificationException错误。
通过源码可知,当调用add方法时,modCount会自增,而再调用迭代器的时候
因为 modCount增加
抛出 ConcurrentModificationException错误
普通for循环,带索引的遍历方式(如果涉及到索引往往用这种遍历方式)
for (int i = 0; i < list.size(); i++) { System.out.println(list.get(i).getAge()+" "+list.get(i).getName()); }
增强for循环,效率最高的遍历方式 格式为for(泛型 别名 :集合或数组对象){}
for (Student s : list) { System.out.println(s.getName()+" "+s.getAge()); }
List集合遍历存储对象的三种方式
最新推荐文章于 2023-05-31 17:01:13 发布