I am trying to iterate through a linked list of objects, doing a comparison of one object that I want to add to the linkedlist with each objects in the linkedlist so that I can find out where to place this new object. I am doing a comparison with both object's get(0) index which is a string and using compareToIgnoreCase(). I am running into an error right after the print statement "looping through linkedlist":
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.LinkedList$ListItr.checkForComodification(Unknown Source)
at java.util.LinkedList$ListItr.next(Unknown Source)
at FileManager.readData(Aclass.java:248)
at Aclass.display(Aclass.java:86)
at Aclass.<init>(Aclass.java:34)
at Aclass.main(Aclass.java:190)
here is iteration:
while(x.hasNext()){
System.out.println("looping through linklist");
//LinkedList<String> obj=x.next(); PROBLEM HERE
if(obj.get(0).compareToIgnoreCase(subData.get(0)) <0){
data.add(c,subData);
System.out.println("ADDED");
c=0;
}
c++; //keeps track of current index of object in linkedlist
}
alternate code:
while(x.hasNext()){
System.out.println("looping through linklist");
LinkedList<String> obj=x.next();
if(obj.get(0).compareToIgnoreCase(subData.get(0)) <0){
System.out.println("ADDED");
break;
}
c++;
}
data.add(c-1,subData);
c=0;
original full code of method:
public LinkedList<LinkedList<String>> readData() {
LinkedList<LinkedList<String>> data=new LinkedList<>();
LinkedList<String> subData=new LinkedList<>();
Iterator<LinkedList<String>> x = data.listIterator(0);
int i=0;
int c=0;
int flag=0;
BufferedReader br = null;
String workingDir = System.getProperty("user.dir");
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(workingDir + "/Data.txt"));
while ((sCurrentLine = br.readLine()) != null) {
if(i==4){
i=0;
if(flag==0){
data.add(subData);
subData=new LinkedList<>();
System.out.println("OK NO SORT");
flag=1;
}
else{
while(x.hasNext()){
System.out.println("looping through linklist");
LinkedList<String> obj=x.next();
if(obj.get(0).compareToIgnoreCase(subData.get(0)) <0){
//data.add(c,subData);
System.out.println("ADDED");
c=0;
}
c++;
}
subData=new LinkedList<>();
System.out.println("added subdata to main linkedlist");
}
}
else {
subData.add(sCurrentLine);
System.out.println("adding to sublist");
i++;
}
}
data.add(subData);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return data;
}