4 lines of mayhem

public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = list.subList(0, 0);
list.addAll(subList);
list.addAll(subList);
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = list.subList(0, 0);
list.addAll(subList);
list.addAll(subList);
}
Throws a ConcurrentModificationException in the last line, and I have no clue why.
8 Replies
JavaBot
JavaBot3y ago
Hey, @Pleezon! Please remember to /close this post once your question has been answered!
Pleezon
PleezonOP3y ago
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = new ArrayList<>(list.subList(0, 0));
list.addAll(subList);
list.addAll(subList);
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = new ArrayList<>(list.subList(0, 0));
list.addAll(subList);
list.addAll(subList);
}
Does not throw an exception
dan1st
dan1st3y ago
sublist doesn't return a copy
Pleezon
PleezonOP3y ago
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = list.subList(0, 0);
list.addAll(new ArrayList<>(subList));
list.addAll(new ArrayList<>(subList));
}
public static void main(String[] args)
{
List<Integer> list = new ArrayList<>();
List<Integer> subList = list.subList(0, 0);
list.addAll(new ArrayList<>(subList));
list.addAll(new ArrayList<>(subList));
}
throws an exception
dan1st
dan1st3y ago
sublist returns a view on the list you cannot iterate and write on the same list at the same time and iterating over the sublist iterates on the original list
Pleezon
PleezonOP3y ago
but like why does List<Integer> subList = list.subList(0, 0); still iterate whilst list.addAll(new ArrayList<>(subList)); runs
dan1st
dan1st3y ago
the problem is iteratimg over the sublist don't use the sublist after the original list changed
Pleezon
PleezonOP3y ago
like.. this copies the sublist right? this does so too one of them works why don't both work :loldog:
Want results from more Discord servers?
Add your server