NoSuchElementException error iterator anylogic [duplicate] - java

This question already has an answer here:
java.util.NoSuchElementException using iterator in java
(1 answer)
Closed 7 years ago.
This is my code:
Iterator<H> iter = ((Main) getOwner()).eH.iterator();
while (iter.hasNext()) {
if (iter.next().z.c > p_l) {
if (r) {
if (iter.next().R) {
if (iter.next().p <= 0.7 * s && iter.next().c_l >= p_l) {
if (s_h == null) {
s_h = iter.next();
} else {
if (iter.next().p <= s_h.price) {
s_h = iter.next();
}
}
}
}
}
}
}
but I am getting this error:
Error during model startup:
java.util.NoSuchElementException
java.util.NoSuchElementException
at java.util.ArrayList$Itr.next(ArrayList.java:839)
at d_w.P.I(P.java:681)
at d_w.P.checkIfI(P.java:649)
at d_w.Main.initModelStructure(Main.java:1072)
at d_w.Main.onStartup(Main.java:2775)
at d_w.Main.start(Main.java:2765)
at com.anylogic.engine.Engine.start(Unknown Source)
at com.anylogic.engine.ExperimentSimulation.r(Unknown Source)
at com.anylogic.engine.ExperimentSimulation.run(Unknown Source)
at d_w.Simulation.executeShapeControlAction(Simulation.java:111)
I really not sure why I am getting this error any suggestion is highly appreciated thanks in advance

Calling .next() will retrieve the next element and advances the iterator. You have multiple .next() calls without checking if there is a next element at all.
If you want to keep using the same element that the .next() initially returned, then, replace the first .next() with H next = iter.next(), then access the next variable.

Every time you call next() you don't get the same element, instead you traverse to the next element of the iterator. You should save this value to a variable and use it.

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

A strange ConcurrentModificationException on iteration

this
is probably the closest case to mine, but that didn't help either.
I'm getting the ConcurrentModificationException here:
for (Iterator<ProjectileBase> iterator = projectiles.iterator(); iterator.hasNext();) {
ProjectileBase proj = iterator.next(); < here
if (proj == null || !proj.isValid()) {
iterator.remove();
continue;
}
if (((!proj.ignoreRange()) ? proj.lived <= proj.data.getRange() : true)){
proj.lived++;
proj.onTick();
} else {
MissileHitEvent event = new MissileHitEvent(proj.shooter, proj.wand, proj, false, null);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
iterator.remove();
continue;
} else {
proj.lived = 0;
}
}
}
Even though I did as suggested here
?
The list is specified like this:
private List<ProjectileBase> projectiles = new ArrayList<ProjectileBase>();
which is intialized on the class construction. What's the problem?
EDIT: console log:
[10:01:58] [Craft Scheduler Thread - 3754/WARN]: Exception in thread "Craft Scheduler Thread - 3754"
[10:01:58] [Craft Scheduler Thread - 3754/WARN]: org.apache.commons.lang.UnhandledException: Plugin MagicWands v1.0 generated an exception while executing task 247
at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:57)
at com.destroystokyo.paper.ServerSchedulerReportingWrapper.run(ServerSchedulerReportingWrapper.java:22)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(Unknown Source)
at java.util.ArrayList$Itr.next(Unknown Source)
at io.jettymc.DataHolders.ProjectileManager.iterate(ProjectileManager.java:117)
at io.jettymc.DataHolders.ProjectileManager$1.run(ProjectileManager.java:232)
at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftTask.run(CraftTask.java:58)
at org.bukkit.craftbukkit.v1_9_R2.scheduler.CraftAsyncTask.run(CraftAsyncTask.java:53)
... 4 more
EDIT 2: Well, I guess it's worth telling, I'm building this project on Bukkit/Spigot (Minecraft server & API).. but I doubt it's the cause of this error?
To help narrow down the problem, there is a trick that might help.
Assuming projectiles is the only reference to the ArrayList, you can temporarily replace it with an immutable list, while you're iterating, so only the Iterator can modify the list. If some other code tries to modify the list, an exception will occur, which should let you know where it happens, assuming your error handling is not messed up.
Example:
List<ProjectileBase> projectilesHold = projectiles;
projectiles = Collections.unmodifiableList(projectiles);
try {
for (Iterator<ProjectileBase> iterator = projectilesHold.iterator(); iterator.hasNext();) {
// other code here is unchanged
}
} finally {
projectiles = projectilesHold;
}
The code saves the modifiable list in the "hold" variable, then wraps the list to make it unmodifiable. The finally block will ensure that the modifiable list is restored, no matter what.
The for loop iterator was then modified to use the modifiable list in "hold", so its remove() method works, but anywhere else the projectiles field is now unmodifiable for the duration of the iteration.
This is for debug only. Once you identify the problem and correct it, remove the logic again.
Check the documentation of ConcurrentModificationException and ArrayList
https://docs.oracle.com/javase/7/docs/api/java/util/ConcurrentModificationException.html
https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
To resolve your issue please check the following code.
For Example,
import java.util.*;
public class HelloWorld{
public static void main(String []args){
List<String> animals = new ArrayList<>();
animals.add("Cat1");
animals.add("Cat2");
animals.add("Cat3");
animals.add("Cat4");
animals.add("Cat5");
for(ListIterator<String> iterator = animals.listIterator(); iterator.hasNext();) {
String name = iterator.next();
if (name.equals("Cat2")) {
iterator.remove();
continue;
}
System.out.println(name);
}
}
}
Cheers!!!

Doubly linked list removing first element [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I'm pretty new to java, and my doubly linked list addFront method and addRear method works fine, but only dequeue method doesn't works. In the main method, I making a test to remove front element using dequeueFront ()method, when I remove front element it works, but If I continued removing front element,
Exception in thread "main" java.lang.NullPointerException
at DoublyLinkedDeque.dequeueFront(DoublyLinkedDeque.java:97)
comes out,
Line97 is the frontNode.previous=null
I just wondering how to remove front element form the double linked list properly.
public E dequeueFront() throws NoSuchElementException
{
if(frontNode!=null)
{
E frontElement=frontNode.element;
frontNode=frontNode.next;
frontNode.previous=null;
frontNode.next=null;
numElement--;
if(numElement==0)
rearNode=null;
return frontElement;
}
else
throw new NoSuchElementException();
}
frontNode=frontNode.next;
If there is no next after frontNode, then frontNode.next returns null.
If frontNode is null then trying to do:
frontNode.previous=null;
Will throw a null pointer exception because how can you access the previous node from a node that doesn't exist? Without thinking about how to make it work with your implementation, just doing a null check will stop this from happening.
if(frontNode != null){
frontNode.previous = null;
}
You will have to do this check with the ".next" also
Or, maybe you can check if numElements = 1. I'll let you think of how to solve that problem.
It should look more like
public E dequeueFront() throws NoSuchElementException {
if(frontNode!=null)
{
E frontElement=frontNode.element;
N oldFront = frontNode ;
frontNode=oldFront.next; // frontNode may now be null
if( frontNode != null ) frontNode.prev=null; // remove link to oldFront
oldFront.previous=null; // should be unessary
oldFront.next = null ;
numElement--;
if(numElement==0)
rearNode=null;
return frontElement;
}
else
throw new NoSuchElementException();
}

ArrayList remove error

I'm working on a project for school but i'm a little stuck right now
My problem is that i have an arrayList of Squares
Each Square has a value(from 0 to 100). Its starting value is 9999 so i can check if its is checked.
If a square is checked i want it to be removed from the arrayList.
So after a while there will be no Squares left.
there is a little bit of code where the first value is set so thats why i check if the value is 9999.
But i get an error. One that i havent seen before.
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException
Vak = Square
this is my code:
while (!vakken.isEmpty()) { // check if empty
Iterator itrVak = vakken.iterator();
while (itrVak.hasNext()) {
Vak vak = (Vak) itrVak.next(); // here is get the error
if (vak.getValue() != 9999) {// check if square value is 9999
Collection checkVakken = vak.getNeighbour().values();
Iterator itre = checkVakken.iterator();
while (itre.hasNext()) {
Vak nextVak = (Vak) itre.next();
if (nextVak != null) {
if (nextVak.getValue() == 9999) {
nextVak.setValue(vak.getValue() + 1); // set value by its neighbour
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
} else {
vakken.remove(vak);
checkvakken.add(vak);
}
}
}
You are removing elements from the collection while you are iterating it. As the iterator may produce unpredictable results in this situation, it fails fast throwing the exception you encountered.
You may only alter a collection through the iterator's methods while traversing it. There should be remove method on the iterator itself, that removes the current element and keeps the iterator intact.
While iterating, you should use Iterator instance for removing object:
itre.remove();
You can try like this:
itre.remove();
ITERATOR never lets you modify when you are iterating.. you need to use loops instead.. this happens coz you are using the Iterator, same time other thread is modifying the list...

Categories

Resources