Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Sort an unmodifiable list

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.

like image 486
Lista Avatar asked Nov 25 '09 15:11

Lista


People also ask

Can we sort Unmodifiable list in Java?

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.

How do you know if a list is Unmodifiable?

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.

What is Unmodifiable list?

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.


3 Answers

    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.

like image 74
Bozho Avatar answered Sep 28 '22 18:09

Bozho


FWIW, with google-collections it's a one-liner:

List<Foo> sorted = Ordering.natural().sortedCopy(unmodifiableList);
like image 22
Kevin Bourrillion Avatar answered Sep 28 '22 19:09

Kevin Bourrillion


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.

like image 39
Mr. Shiny and New 安宇 Avatar answered Sep 28 '22 19:09

Mr. Shiny and New 安宇