I'm trying to add an Integer to an array list using and iterator. It crashes at the third call to .next() of the iterator. Here is the stack trace and code
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:886)
at java.util.ArrayList$Itr.next(ArrayList.java:836)
at quicksort.test.generateSorted(test.java:33)
at quicksort.test.main(test.java:17)
Java Result: 1
public static int[] generateSorted(final int length, final int minVal, final int maxVal)
{
ArrayList<Integer> data = new ArrayList<>(length);
data.add(getRandomVal(minVal, maxVal));
ListIterator<Integer> itr = data.listIterator();
boolean added;
for(int i = 0; i < length; i++)
{
added = false;
int rndNum = getRandomVal(minVal, maxVal);
while(itr.hasNext() && !added)
{
System.out.println(rndNum);
Integer currentNum = itr.next();
if(currentNum >= rndNum)
{
itr.add(rndNum);
added = true;
}
}
if(!added)//add to end of arrayList
data.add(rndNum);
}
return data.stream().mapToInt(i -> i).toArray();
}
How can it be a concurrent modification when everything in the project is single threaded? If an itterator can't add
As an aside, what's the difference between new ArrayList<>(size) and new ArrayList(size)? Netbeans gives me a warning with the second but still compiles fine.
EDIT: oops typo, I also meant to ask what the difference is with ArrayList(size)
new ArrayList<>(size)uses type inference to work out what the generic type of the ArrayList is, whilenew ArrayList(size)creates a raw (untyped) ArrayList. You should always use typed generics wherever possible so that you have type safety.new ArrayList<Integer>(size)and not having anything whereIntegeris?ArrayList<Integer> data, so making you define it again when you instantiate it is unnecessary - the compiler can work it out for itself. It's known as the diamond operator, and is effectively just shorthand for what you used to write.