I’m trying to remove a particular element from Arraylist, it throws an ConcurrentModificationException
ArrayList<String> ar = new ArrayList<String>(); ar.add("a"); ar.add("b"); ar.add("c"); ar.add("a"); ar.add("e"); for(String st: ar){ System.out.println("st="+st); if(st.equals("a")){ ar.remove(st); } }
any comments, what am I doing wrong?
Advertisement
Answer
Only remove an element from the array while iterating by using Iterator.remove()
.
The line for(String st: ar) {
is a bit misleading. You’re actually creating an iterator behind the scenes which is being used for this iteration. If you need to remove elements from within the iteration, you need to explicitly use an iterator so that you can call iterator.remove()
.
ArrayList<String> ar = new ArrayList<String>(); ar.add("a"); ar.add("b"); ar.add("c"); ar.add("a"); ar.add("e"); Iterator<String> it = ar.iterator(); while (it.hasNext()) { String st = it.next(); System.out.println("st="+st); if (st.equals("a")) { it.remove(); } }