今天用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