Could someone exlain to me why the following code results in the programm being terminated immediately? There's almost nothing to go by in the console or debug tab.
Thanks in advance!
@bowmore: Thank you, that was one error. However, when I add to the ListIterator instead, I'm getting an OutOfMemory: Java heap space exception.
package Buchalka1;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.ListIterator;
public class LinkedList2 {
//--------------------------------------------------------------------------------------------------
public static void main(String[] args)
{
LinkedList<String> letters = new LinkedList<String>();
addInOrder(letters, "D");
addInOrder(letters, "A");
addInOrder(letters, "B");
printList(letters);
}
//--------------------------------------------------------------------------------------------------
public static void printList(LinkedList<String> list)
{
Iterator<String> iterator1 = list.iterator();
while (iterator1.hasNext()) {
System.out.println("Entry: " + iterator1.next());
}
System.out.println("-----------------------------------------------------");
}
//--------------------------------------------------------------------------------------------------
public static void addInOrder(LinkedList<String> list, String newEntry)
{
ListIterator<String> listIterator1 = list.listIterator();
while(listIterator1.hasNext()) {
int comparison = listIterator1.next().compareTo(newEntry);
if (comparison == 0) {
// newEntry should not be added, because already present.
System.out.println(newEntry + " is already part of the list.");
} else if (comparison > 0) {
// newEntry should be listed before the iterator's current entry.
listIterator1.previous();
listIterator1.add(newEntry);
} else if (comparison < 0){
}
}
listIterator.add(newEntry);
}
//--------------------------------------------------------------------------------------------------
}
Console:
- Exception in thread "main" java.util.ConcurrentModificationException at java.util.LinkedList$ListItr.checkForComodification(LinkedList.java:966) at java.util.LinkedList$ListItr.next(LinkedList.java:888) at Buchalka1.LinkedList2.addInOrder(LinkedList2.java:34) at Buchalka1.LinkedList2.main(LinkedList2.java:15)
Debug:
- terminated LinkedList2 [Java Application]
- terminated, exit value: 1>D:\Programs\java\jdk1.8\bin\javaw.exe (17.12.2019, 16:14:44)