Why does Collections.sort(List) work in Java 8 with CopyOnWriteArrayList but not in Java 7? -


i can sort list of users without problems using following code , java 8:

copyonwritearraylist<user> allcurrentloginneduserslist = new copyonwritearraylist<>();  collections.sort(allcurrentloginneduserslist); 

now, changed java 7 , saw no errors on eclipse. now, when running under java 7 got error:

java.lang.unsupportedoperationexception     @ java.util.concurrent.copyonwritearraylist$cowiterator.set(copyonwritearraylist.java:1049)     @ java.util.collections.sort(collections.java:221)     @ com.fluent.user.sortallcurrentloginnedusers(user.java:446) 

how fix it?

there change between java 7 (and version of java 8) , java 8u20 in way collections.sort work (issue 8032636, noted holger).


java 7 collections.sort(list, c) specifies that:

this implementation dumps specified list array, sorts array, , iterates on list resetting each element corresponding position in array. avoids n² log(n) performance result attempting sort linked list in place.

looking @ code, done obtaining listiterator list. however, copyonwritearraylist listiterator() method states iterator returned not support set operation:

the returned iterator provides snapshot of state of list when iterator constructed. no synchronization needed while traversing iterator. the iterator not support remove, set or add methods.

this explains error getting when running code java 7. workaround, can refer this question answer dump content of list array, sort array , put elements in list.


in java 8, collections.sort(list, c) changed implementation:

this implementation defers list.sort(comparator) method using specified list , comparator.

and new method copyonwritearraylist.sort(c) (introduced in java 8) not use list iterator works correctly.


Comments

Popular posts from this blog

c++ - llvm function pass ReplaceInstWithInst malloc -

Cross-Compiling Linux Kernel for Raspberry Pi - ${CCPREFIX}gcc -v does not work -

java.lang.NoClassDefFoundError When Creating New Android Project -