-1

I wrote a program which is throwing ConcurrentUpdateException , I am unable to understand this behavior, It should not through any exception as i have only single thread to work with and i have not taken any iterator.

What happens in, sorting ? Why it is throwing this exception ? Please explain.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Test {
        public static void main(String[] args) {
        List<Double> list1 = new ArrayList<Double>(Arrays.asList(3., 2., 0., 1., 2.));
        List<Double> subList = list1.subList(0, 3);
        Collections.sort(list1);
        System.out.println(subList.get(0));

    }
}
T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • Can you add the stacktrace ? and what is `3., 2., 0., 1., 2.` ? – Suresh Atta Apr 24 '17 at 06:00
  • there´s no exception when executing the code locally for me. it just outputs `0.0` – SomeJavaGuy Apr 24 '17 at 06:01
  • 1
    As @Sergey points out, subList() returns a view which is backed by the original list. Any structural changes to the original list will make the view undefined (since, for example, if you want elements 0 to 3 of the original list in your sub list and you sort the original list, the elements would no longer be the ones you originally requested). The ConcurrentUpdateException is a bit misleading, as it seems to indicate a multithreading problem. Instead, it is thrown when an explicit test for modifications of the parent list is positive. – Markus Fischer Apr 24 '17 at 06:31

1 Answers1

0

Function subList returns a view of the specified range within this list. So when you sort collection, subList will also change. That's why you get 0.0, and not 3.0.

Sergey
  • 176
  • 2
  • 12