java中对集合操作的易错点01
今天用for循环遍历集合,对集合中满足条件的元素进行remove操作报错:ConcurrentModificationException
所以,在遍历集合进行增、删操作时,要使用迭代器的方式
public static void main(String[] args) { IwbUsage iu = new IwbUsage(); iu.setIp("100"); List<IwbUsage> iuList = new ArrayList<>(); iuList.add(iu); System.out.println(iuList.size()); Iterator<IwbUsage> iterator = iuList.iterator(); while(iterator.hasNext()) { IwbUsage iwbUsage = iterator.next(); System.out.println(iwbUsage); if ("10".equals(iwbUsage.getIp())) { iterator.remove(); } } System.out.println(iuList.size()); }
注意:要使用迭代器进行删除iterator.remove();不可以用迭代器遍历集合时用集合的删除方式iuList.remove(iwbUsage )否则会抛异常:ConcurrentModificationException