Parallel elimination of modification when sorting

I wrote this little sorting program arrays

. As I understand it, it should print 0,1,2

.

However, when I run this program, I get ConcurrentModificationException

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

      

I'm really not sure about the root cause of this exception.

Can someone help me understand where I am going wrong?

Note. This problem does not exist in JAVA 7. It would be great if someone could explain why it is in JAVA 8 and not in JAVA 7

+3


source to share


2 answers


The API docs List.subList

say:

The semantics of the list returned by this method becomes undefined if the backing list (i.e. this list) is structurally modified in any way other than through the returned list. (Structural changes are those that change the size of this list, or otherwise disturb it in such a way that the iterations performed may give incorrect results .)



Sorting will indeed change the list in such a way that the iterations performed will produce incorrect results. The API docs say it is undefined in this case - in practice this means that a ConcurrentModificationException

is called (at least when using Java 8) as your code shows.

+7


source


List.sublist returns a view of a portion of the list, so you cannot modify the original list. If you want it to work, you need to rewrite subscriptions to a new list object:

        List<Double> l1 = new ArrayList<>(Arrays.asList(2.0, 0.0, 1.0));
        List<Double> l2 = new ArrayList<>(l1.subList(0, 3));
        Collections.sort(l1);
        System.out.println(l2.get(0));

      



Otherwise l2 vaues will change after the sort operation, which would be unwanted and java will not allow it.

0


source







All Articles