Reputation: 139
I am trying to remove some objects from a List while iterating over the list. To avoid, ConcurrentModificationException, I am using an Iterator and calling remove(). This part of the code looks like the following.
Iterator<ClassName> it = classList.iterator();
while(it.hasNext()) {
ClassName obj = it.next();
if(obj.getData() == 1) {
it.remove(obj);
}
}
I get the following error: remove() in java.util.Iterator cannot be applied to (ClassName). I have two questions
Upvotes: 0
Views: 1797
Reputation: 15698
The method remove doesn't take any arguments , try
it.remove();
There is no harm in removing object while iterating from the List if you are using Iterator but calling directly myList.remove(obj/index)
can result in ConcurrentModificationException. Care should be taken when you are in multi-threaded environment.
Upvotes: 0
Reputation: 121998
Why do I get this compilation error and how to fix it?
You need not to pass an object to it. Current object will be remove directly. it.remove()
is enough
Is it a good practice (or even safe) to remove objects from a list while iterating over the list?
Yes. That is fine to iterate and remove an element from it. What not good practice/safe is removing directly from list object instead of iterator. When you try to remove from list directly and looping on it, that leads to ConcurrentModificationException
.
Upvotes: 0
Reputation: 1373
Try it.remove() as mentioned by many Answers, and yes you can remove the objects and it is safe to remove while iterating over list.
Upvotes: 0
Reputation: 8975
There is no method of iterator which takes arguements as object.
Iterator<ClassName> it = classList.iterator();
while(it.hasNext()) {
ClassName obj = it.next();
if(obj.getData() == 1) {
it.remove();
}
}
Iterator.remove() is safe.
Note that Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.
is from:
http://docs.oracle.com/javase/tutorial/collections/interfaces/collection.html
Upvotes: 0
Reputation: 35547
You should call remove()
in iterator which takes no arguments.
Iterator<ClassName> it = classList.iterator();
while(it.hasNext()) {
ClassName obj = it.next();
if(obj.getData() == 1) {
it.remove();
}
}
Yes iterator is the way to remove object while iterating.
Upvotes: 0
Reputation: 420921
1. Why do I get this compilation error and how to fix it?
Do it.remove()
(and don't give it any arguments). The method will remove the current object from the underlying collection.
2. Is it a good practice (or even safe) to remove objects from a list while iterating over the list?
Yes. This is a perfectly fine way to remove objects from a collection.
Upvotes: 2