I have the following code
boolean postojaoJePrijelaz = true;
epsilonStanja = sljedecaStanja;
while(postojaoJePrijelaz) {
for (String epsilonStanje : epsilonStanja) {
for (Prijelaz trenutniPrijelaz : prijelazi) {
postojaoJePrijelaz = false;
if (trenutniPrijelaz.postojiPrijelaz(epsilonStanje.trim(), "$")) {
sljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
epsilonSljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
postojaoJePrijelaz = true;
}
}
}
epsilonStanja = epsilonSljedecaStanja;
epsilonSljedecaStanja.clear();
}
And the compiler gives e ConcurrentModificationException even though i set epsilonStanje=epsilonSljedecaStanja after I already finished my foreach loop. I tried debuggng, but can't seem to fix this.
The program that I'm making is single-threaded
EDIT:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859)
at java.util.ArrayList$Itr.next(ArrayList.java:831)
at com.company.Main.main(Main.java:55)
epsilonStanja and epsilonStanja both are pointing to the same object as shown below.
epsilonStanja = sljedecaStanja;
for (String epsilonStanje : epsilonStanja) {
...
sljedecaStanja.addAll(trenutniPrijelaz.getSkupIzlaznihStanja());
...
}
you can't add data while iterating.
Solution: create a separate list and finally merge it as per your requirement or try below code:
epsilonStanja.addAll(sljedecaStanja);
you are assigning the reference of list sljedecaStanja to epsilonStanja. This is the issue.. Try
epsilonStanja = new ArrayList<String>(sljedecaStanja);
Related
Hi I have this piece of code which is giving me trouble:
StmtIterator iter2 = model.listStatements(new SimpleSelector(null, FOAF.family_name, (RDFNode) null) {
public boolean selects(Statement s) {
// return the statements whose object equal to the required place
return s.getString().toLowerCase().equals(latin.toLowerCase());
}
});
if (iter2.hasNext()) {
while (iter2.hasNext()) {
Statement s = iter2.nextStatement();
// s.getSubject().addProperty(FOAF.family_name, maltese, "mt");
}
}
The commented line is the line throwing the exception. Any idea why this is happening?
This is the whole error output:
Exception in thread "main" java.util.ConcurrentModificationException
at com.hp.hpl.jena.mem.HashCommon$BasicKeyIterator.hasNext(HashCommon.java:354)
at com.hp.hpl.jena.util.iterator.NiceIterator$1.hasNext(NiceIterator.java:103)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.Map1Iterator.hasNext(Map1Iterator.java:48)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at com.hp.hpl.jena.util.iterator.FilterIterator.hasNext(FilterIterator.java:54)
at com.hp.hpl.jena.util.iterator.WrappedIterator.hasNext(WrappedIterator.java:90)
at NotarialArchivesTurtle.main(NotarialArchivesTurtle.java:643)
The problem seems to be caused because I am adding a property the same as the one I was searching for ie: family_name
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
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!!!
I'm trying to build an application in Android using some codes from Objective-C (IPhone app).I'm trying to understand what exactly is doing a piece of code and translate it into Java code,but I think I need a little help here.So first, here is the Obj-C code :
(BOOL)processSqlInjectQueries:(NSArray *)injectQueries error:(NSError**)error {
//some code
for(NSDictionary * q in injectQueries)
{
if (![q isKindOfClass:[NSDictionary class]]) continue;
StPacketInjectQueryPackage qType = (StPacketInjectQueryPackage)[[q objectForKey:#"type"] intValue];
NSString * query = [q objectForKey:#"query"];
}
//some code
}
In Java, I'm trying to do something like this :
// in some other method :
JSONObject jsonData= new JSONObject();
String authHash = jsonData.getJSONObject("client_auth_hash").toString();
List<Map<String,String>> injectQueries= new ArrayList<Map<String,String>>();
injectQueries.add(new HashMap<String, String>());
//injectQueries.add(authHash);
public boolean processSqlInjectQueries(List<Map<String,String>> injectQueries, Exception error){
if(injectQueries==null || injectQueries.size()==0){
boolean injectsProcessed = this.processSqlInjectQueries(injectQueries,error);
if(!injectsProcessed){
return false;
}
}
Log.i("Info","Processing INJECT Queries...");
boolean res = true;
/*[_dbAdapter beginTransaction];
[_user.userDbAdapter beginTransaction];*/
for(Map<String,String> b : injectQueries){
if(b.getClass().getName()!=injectQueries.getClass().getName()){
continue;
}
//RPCPacketInjectQueryPackage qType = (RPCPacketInjectQueryPackage)
}
return true;
}
But my problem is that is that I get this error : Type mismatch: cannot convert from element type Object to ArrayList.
Any suggestion how to fix that error?
And second question : Can I use Exception error in declaraion of processSqlInjectQueries instead of NSError *error in Obj-C?
Iterating over the ArrayList
The error is being raised because your code needs to declare that b is an Object (since injectQueries contains objects of type Object, not objects of type ArrayList):
for(Object b : injectQueries){
...
}
Since the NSDictionary class in Objective-C closely resembles the Map class in Java, you can mimic the Objective-C code by casting b as a Map, or even better, you can use generics to specify that injectQueries contains Map objects. For example:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries, Exception error) {
// some code
for(Map<String,String> b : injectQueries) {
...
}
// some code
return true;
}
Exception Handling
As for your second question, methods in Java normally communicate error conditions by throwing Exception objects, so your method signature would resemble the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception
Note that it's always better to be specific with your exceptions (i.e. to throw objects that are subclasses of Exception) so that your method caller has some idea of what went wrong. See the following link for additional guidelines for handling exceptions in Java:
http://www.javapractices.com/home/HomeAction.do#Exceptions
The objective C code is passing through an NSArray containing NSDictionaries through to the method, so the following is probably closer to what you want to do...
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
}
To handle the error code, you probably want to think about throwing an exception rather than trying to pass through an "Error" object, so something like the following:
public boolean processSqlInjectQueries(List<Map<String,String> injectQueries) throws Exception {
for(Map<String,String> q : injectQueries) {
// do stuff with q
}
if(errorConditionOccurs) {
throw new Exception();
}
}
You'll want to tailor the exact Exception that's thrown so it matches whatever your code is trying to do.
In response to comment: perhaps this is closer to what you're trying to do?
public boolean processSqlInjectQueries(JSONObject jsonObject) {
for(String key : jsonObject.keys()) {
Object value = jsonOnject.get(key);
// Do stuff with value
}
// Do more stuff
}
And you could call it with:
processSqlInjectQueries(jsonData.getJSONObject("client_auth_hash"));
I am struggling with this error. I feel its really simple but cannot understand why am getting the error.
I keep getting a NullPointerException when I iterate through values in my linked list.
Code Snippet:
private void updateBuyBook(LimitOrder im) {
LimitOrder lm = null;
Iterator itr = buyBook.entrySet().iterator();
boolean modify = false;
while (itr.hasNext() && !modify) {
Map.Entry pairs = (Map.Entry) itr.next();
if ((((LinkedList<IMessage>) pairs.getValue()).size() > 0)) {
LinkedList<ILimitOrder> orders = (LinkedList<ILimitOrder>) pairs
.getValue();
ListIterator listIterator = orders.listIterator();
while (listIterator.hasNext() && !modify) {
LimitOrder order = (LimitOrder) listIterator.next();
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) { // error at this line
lm = order;
addToBuyMap(im);
modify = true;
break;
}
}
if (modify = true) {
orders.remove(lm);
break;
}
}
}
}
Error is at this line:
Exception in thread "main" java.lang.NullPointerException
order.getOrderID().equalsIgnoreCase(im.getOrderID()));
Please help. Is my assignment wrong in any way???
Please help!!!
Thanks
Changing your code a bit will make it longer, but much easier to find the error... instead of doing:
if (order.getOrderID().equalsIgnoreCase(im.getOrderID())) {
Change it to:
String orderID = order.getOrderID();
String imOrderID = im.getOrderID();
if(orderID.equals(imOrderID()) {
Then you will know if order or im is null. If neither of those is null then the things that could be null are orderID and imOrderID. It is now a simple matter of finding out which one of those is null.
If it is order or im then the program will crash on the order.getOrderID() or im.getOrderID() lines.
If, instead it is orderID or imOrderID that is null, then it will crash on if(orderID.equals(imOrderID()) {. You can then use System.out.println (or something better, like a debugger) do easily find out what is wrong.
If neither of those should be null then I suggest adding something like:
if(orderID == null) { throw new IllegalStateException("orderID cannot be null"); }
if(imOrderID == null) { throw new IllegalStateException("imOrderID cannot be null"); }
and then track down how it got set to null to begin with.
My guess would be that you're passing in the null, into im. I'll need to see more of the code to be sure.
You never check to see if im is null. I suspect it is.
One first look, where is im instantiated? You can also try to debug in your IDE so as to see whats going on?
Either im is null or order.getOrderID() is returning null.
Doesn't look like im is ever declared / assigned. So
im.getOrderID()
is probably where the null pointer exception is generated.
-- Dan
Edit:
Missed that im is passed in as an argument. So that leaves a few possibilities (in order of likelihood):
im is null (ie. user called function with null parameter)
order.getOrderID() is returning null
order is null (ie. the list has nulls in it)
Edit2:
Your line
if (modify = true)
Is fundamentally wrong and will always evaluate to true (single equal is for assignment, == is for comparison.)
When simply checking if a flag boolean is true or false, it is best to use:
boolean flag = true;
if(flag)
{
// True block
}
else
{
// False block
}
It will be good if you could add a debug point before that line and see which variable is null. looking at the code the answer is 1. order is null 2. order.getOrderID() is null or 3. im is null