Java Remove Element from ArrayList

To remove some elements from an ArrayList while iterating over the ArrayList, we need to use Iterator. Integer[] arr = {1,2,3,4,5,6}; ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr)); System.out.println(list);   Iterator<Integer> iter = list.iterator(); while(iter.hasNext()){ int i = iter.next(); if(i==5) iter.remove(); }   System.out.println(list);Integer[] arr = {1,2,3,4,5,6}; ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(arr)); System.out.println(list); Iterator<Integer> iter = list.iterator(); … Read more

java.util.ConcurrentModificationException

This post shows show to solve the problem of java.util.ConcurrentModificationException for ArrayList. The error message looks like the following: Exception in thread “main” java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source) … … The Problem You may want to iterate through an ArrayList, and delete some element under some certain condition. For example, the following code … Read more