今天用for循环遍历集合,对集合中知足条件的元素进行remove操做报错:ConcurrentModificationExceptionhtml
因此,在遍历集合进行增、删操做时,要使用迭代器的方式spa
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 )不然会抛异常:ConcurrentModificationExceptioncode