How do you remove objects from Java collections like ArrayList, while iterating is one of the frequent questions my reader asked me in my post about Top 25 Java Collection Interview Questions. Well, this question may seem quite easy, because of every java.util.Collection implementation like List or Set has remove() method to delete a particular object, which can be used to remove elements from any Collection like ArrayList, LinkedList, or Vector. Well, this is where things go wrong and interviewers are interested to see, whether you can point out the remove() method from Iterator or not.
The answer to this question is as simple as that, you should be using Iterator's remove() method to delete any object from Collection you are iterating, but this is not the end of this question.
Most likely you will be asked to explain, what is a difference in removing objects using the remove() method of Collection over remove() method of Iterator and why one should use over the other?
The reason is ConcurrentModificationException, if you use the remove() method of List, Set, or basically from any Collection to delete object while iterating, it will throw ConcurrentModificationException.
Though remove() method of java.util.Collection works fine to remove individual objects, they don't work well when you are iterating over a collection. Let's see a code example to clear doubts
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
The answer to this question is as simple as that, you should be using Iterator's remove() method to delete any object from Collection you are iterating, but this is not the end of this question.
Most likely you will be asked to explain, what is a difference in removing objects using the remove() method of Collection over remove() method of Iterator and why one should use over the other?
The reason is ConcurrentModificationException, if you use the remove() method of List, Set, or basically from any Collection to delete object while iterating, it will throw ConcurrentModificationException.
Though remove() method of java.util.Collection works fine to remove individual objects, they don't work well when you are iterating over a collection. Let's see a code example to clear doubts
And, If you are new to the Java world then I also recommend you go through The Complete Java MasterClass on Udemy to learn Java in a better and more structured way. This is one of the best and up-to-date courses to learn Java online.
How to Remove elements From ArrayList while Iterating? Example
In the below code, we have a list of exchanges and we are removing exchanges that are closed at the moment. Code is as simple as it could be and it's hard to find anything wrong with it by just looking, but things will be different when you run it.You will be hit by ConcurrentModificationException, as soon as you run, because here are we are using the remove() method of ArrayList to remove objects, instead of the Iterator's remove method. In order to fix ConcurrentModificationException, just use the remove() method of java.util.Iteator class.
And, here is our complete Java program to test and confirm this behavior. This program demonstrates that if you use the Collections remove method while traversing over Collection using Iterator to remove the current element then you can get ConcurrentModificationException and by using Iterator's remove method you can easily avoid it.
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Java program to demonstrate how to remove the object from List and difference
* between Iterator's remove() method and Collection's remove() method in Java
*
* @author http://javarevisited.blogspot.com
*/
public class ObjectRemovalTest {
public static void main(String args[]) {
List markets = new ArrayList();
StockExchange TSE = new StockExchange(){
@Override
public boolean isClosed() {
return true;
}
};
StockExchange HKSE = new StockExchange(){
@Override
public boolean isClosed() {
return true;
}
};
StockExchange NYSE = new StockExchange(){
@Override
public boolean isClosed() {
return false;
}
};
markets.add(TSE);
markets.add(HKSE);
markets.add(NYSE);
Iterator itr = markets. iterator();
while(itr.hasNext()){
StockExchange exchange = itr.next();
if(exchange.isClosed()){
markets.remove(exchange); //Use itr.remove() method
}
}
}
}
interface StockExchange{
public boolean isClosed();
}
Output
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at ObjectRemovalTest.main(StringReplace.java:63)
Java Result: 1
To be frank, even with the use of modern IDE like Eclipse, you may code is wrong, and end up confusing yourself when you see ConcurrentModificationException because that sometimes mislead programmers.
It looks that may be another thread is modifying the collection, and with this thought, you won't look at the code you are using for traversing ArrayList. If you want to learn more about Collections in Java then I also suggest you check out these Java Collections and Stream Courses, where I have shared the best courses to learn this important framework.
That's why sometimes interviewers present the code and asks you to find bugs on it, or they may simply ask you to write code for removing objects from Collection while traversing over them. Always remember to use Iterator's remove() method for removing objects from Collection in Java.
Other Java Collection tutorials you may like
- How to sort a Map by keys and values in Java? (tutorial)
- How to sort an ArrayList in ascending and descending order in Java? (tutorial)
- What is the difference between ArrayList and HashSet in Java? (answer)
- What is the difference between TreeMap and TreeSet in Java? (answer)
- What is the difference between HashMap and ConcurrentHashMap in Java? (answer)
- The difference between HashSet and TreeSet in Java? (answer)
- The difference between ArrayList and LinkedList in Java? (answer)
- The difference between Vector and ArrayList in Java? (answer)
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.
3 comments :
good article, thanks! One typo is itr.next() has to be casting to StockExchange in the while loop.
Its better to use remove(index) if know the index of the object you want to remove, because then its not required to search that element in array. Only use remove(Object) if you don't know the index. See here to learn more about how to remove elements from an ArrayList.
I usually remove element by a reverse looping.
for(int i=list.size()-1;i≥0;i--)
if(.....)
list.remove(i);
Post a Comment