How would one do this?
I have tried creating a new, empty list, then copying unmodifiable list's elements to it, but I'm getting unsupported operation error.
Any help is appreciated.
Of course you can't sort an unmodifiable List, because it has to be rewritten with add and delete operations, and those are not allowed.
I suggest using "addAll(Collections. emptyList());" instead of add(null) to test for immutable. This will raise the UnsupportedOperationException if immutable and does not modify the list if mutable.
The unmodifiableList() method of Java Collections class is used to get an unmodifiable view of the specified list. If any attempt occurs to modify the returned list whether direct or via its iterator, results in an UnsupportedOperationException.
List unmodifiableList = Collections.unmodifiableList(list); List newList = new ArrayList(unmodifiableList); Collections.sort(newList);
The constructor of ArrayList
takes an existing list, reads its elements (without modifying them!), and adds them to the new List.
FWIW, with google-collections it's a one-liner:
List<Foo> sorted = Ordering.natural().sortedCopy(unmodifiableList);
Are you creating an empty list using Collections.emptyList()
? If so, that is an unmodifiable list too and that may be the source of your problem.
Create a new list using the constructor for your List implementation, such as new ArrayList()
. You can pass the original list into the constructor or else use the addAll()
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With