java.util.ConcurrentModificationException - How do I delete using an iterator [duplicate] - java

This question already has answers here:
How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList
(24 answers)
Closed 5 years ago.
Using the following code will result in a java.util.ConcurrentModificationException
final AnimationTimer timer = new AnimationTimer() {
#Override
public void handle(long timestamp) {
for (ListIterator<myCircle> List = CircleList.listIterator(); List.hasNext(); ) {
myCirle check = List.next();
if (CheckCollisionFunction(check) == true) {
this.stop();
CircleList.clear();
gameOverFunction();
}
}
}
}
So im using an iterator to check if any of my circles are colliding with my player circle.
When I clear the list:
CircleList.clear();
I get the exception.
java.util.ConcurrentModificationException
Which is when you delete sometimes outside an iterator when using an iterator. Can someone please show me how to delete everything in my list using the iterator?
Or another way to stop this error.
This is my list.
private final ObservableList<myCircle> CircleList = FXCollections.observableArrayList();

Simply insert a break; after gameOverFunction(); to stop the iterator.
The problem is that you clear the list, but the iterator continues, and on the next next() call the exception will be thrown.

Related

Concurrent Exception on Iterator.next() in Java [duplicate]

This question already has answers here:
Why is a ConcurrentModificationException thrown and how to debug it
(8 answers)
Closed 1 year ago.
This is a code snippet to move to next element in the linked list. On debugging, itrPlaylist.next() is triggering a ConcurrentModificationException. I read that the list should not be modified while I am iterating. So, in this case, where did I go wrong? How can it be resolved?
Thanks in Advance.
public boolean nexxt() {
if(this.itrPlaylist.hasNext())
{
if(!bForward)
{
bForward = true;
itrPlaylist.next();
}
System.out.println("Now playing : " + itrPlaylist.next());
return true;
}
else
{
System.out.println("Reached end of " + this.getPlaylistName() + " playlist !");
}
return false;
}
Where is itrPlaylist is defined? Somethng like
itrPlaylist = list.iterator();
Above assignment should have happened after all the inserts have been done to the list. Looks like you have created one instance variable for itrPlaylist. And I think you might be doing
list.add(value);
after itrPlaylist has been initialized.
In that case, code will throw the above mentioned exception. This happens when some other code outside of iterator modifies the list when iterator is already initialized.

ConcurrentModificationException -> How can I change my code to stop it from throwing this error? [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 5 years ago.
for (FPlayer p : fPlayer.getFaction().getOnline()) {
p.setFaction(null);
}
Basically, the getOnline method returns an array list of the current FPlayers that are online. When the FPlayer is removed from their faction, the faction is set to null (p.setFaction(null)).
I cannot think about how to change my code to stop it from throwing the ConcurrentModificationException. I have used an iterator but still, it.next().setFaction(null) still throws the same exception.
EDIT:
USING A LIST ITERATOR:
ListIterator<FPlayer> it = fPlayer.getFaction().getOnline().listIterator();
while (it.hasNext()) {
it.next().setFaction(null);
}
Caused by: java.util.ConcurrentModificationException
At the line
it.next().setFaction(null)
EDIT #2:
Set faction method:
public void setFaction(Faction faction) {
if (hasFaction()) {
this.faction.getOnline().remove(this);
}
this.faction = faction;
if (faction != null) {
this.faction.getOnline().add(this);
}
}
This is happening because while iterating you are removing the data from the list .
Couple of solutions .
If the list size is small convert it to array and then loop over
Use for loop for iteration .
for(int i=0;i<fPlayer.getFaction().getOnline().size();i++)
{
// Condition to check if true
if(true)
{
fPlayer.getFaction().getOnline().remove(i);
i--;
}
}
Yes, change your code so it doesn't change the collection inside the loop you are running. For example, create a copy of the collection before iterating.
for (Foo foo : new ArrayList(myFoos)) {
if (foo.isBar()) {
myFoos.remove(foo);
}
}
Iterating and changing the list without the new ArrayList() would have caused a ConcurrentModificationException

ConcurrentModificationException in iterator.next() Multithreaded [duplicate]

This question already has answers here:
ConcurrentModificationException when using iterator and iterator.remove()
(4 answers)
Closed 6 years ago.
I have created this simple worker thread to calculate palindromes by iterating through an ArrayList.
I get an Error when I execute line temp_str1 = it.next();.
The ArrayList buffer_List is not used by any other thread hence using synchronized block does not help. I have looked through previous questions and they did not help much. I would eager to find the solution to this problem.
Here is My code:
private void find_Palindromes(ArrayList<String> buffer_List){
Iterator<String> it = buffer_List.iterator();
String temp_str1, temp_str2;
while(it.hasNext()){
temp_str1 = it.next();
//System.out.println(temp_str1);
it.remove();
if(is_Palindrome(temp_str1)){
to_Shared_Queue(temp_str1);
palin_count++;
}
}
}
Edit Code : added to_Shared_Queue
private void to_Shared_Queue(String str){
synchronized(shared_queue){
Shared_queue.add(str);
}
}
It is because of you modifying iterator while looping over it . you can do it by remove it from your array buffer_List.
buffer_List.remove(temp_str1);

Java - weird ConcurrentModificationException [duplicate]

This question already has answers here:
Java Set gets full
(2 answers)
Closed 8 years ago.
I loop through a copy of a set of objects, but it still gives me an error starting at this method:
private static Set<Updated> updates = new HashSet<>();
public static Set<GameObject> getGameObjects() {
Set<GameObject> objs = new HashSet<>();
for (Updated up : new HashSet<Updated>(updates)) {
if (up instanceof GameObject)
objs.add((GameObject) up);
}
return objs;
}
(Where the for loop is).
This only happens when there are quite a few GameObjects, and never occurs when there's only a few (like 7). Thank you!
The problem is that somebody in another thread changes the updates set while it is being copied in new HashSet<Updated>(updates).
You cannot do this without synchronization. Or use ConcurrentHashMap instead of HashSet

Linkedlist error when removing using an iterator [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
LinkedList iterator remove
private LinkedList flights;
...
public FlightQueue() {
super();
flights = new LinkedList();
}
...
public void clear(){
ListIterator itr = flights.listIterator();
while(itr.hasNext()){
itr.remove();
}
}
....
Exception in thread "main" java.lang.IllegalStateException
at java.util.LinkedList$ListItr.remove(Unknown Source)
at section1.FlightQueue.clear(FlightQueue.java:44)
at section1.FlightTest001.main(FlightTest001.java:22)
No idea whats wrong, its showing the error at the first itr.remove().
From the iterator API:
IllegalStateException - if the next method
has not yet been called, or the remove method has already been called
after the last call to the next method
you have to call iterator.next() before calling iterator.remove().
while(itr.hasNext()){
itr.next(); //This would resolve the exception.
itr.remove();
}
You can call itr.remove() only if you called next() or previous() before, because it removes an element that was returned by those methods.
public void clear(){
flights.clear();
}
Use clear() method of LinkedList
Have a look at the Javadoc for ListIterator. It specifically states:
IllegalStateException - neither next nor previous have been called,
or remove or add have been called after the last call to next or previous.
You'll need a .next() before the .remove() in your posted code fragment.
Cheers,

Categories

Resources