简体   繁体   中英

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.

FWIW,使用google-collections是单行的:

List<Foo> sorted = Ordering.natural().sortedCopy(unmodifiableList);
    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.

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.

In Java 8, you can use the streams API. For instance:

List<?> sortedList = unsortedList.stream().sorted().collect(Collectors.toList());

Since Java 16, a Stream.toList() function was added, so the above can be shortened to:

List<?> sortedList = unsortedList.stream().sorted().toList();

It should work as described. Elements in an unmodifiable List are not unmodifiable themselves. 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.

Guess the error is somewhere else, best would be to show your code :)

I will answer your second question:

You cannot add to your 'taskListModifiable' list because that is an 'unmodifiable' list, which in Java means that it is immutable. An unmodifiable/immutable list or collection of any kind cannot be directly changed in any way - you cannot add elements to it, remove elements from it, or change references to existing elements.

Note that existing elements in the list/collection may be changed if they are themselves mutable, but references to them from the list cannot be changed. That is, until the list goes completely out of scope and is garbage collected, the unmodifiable list will always contain those same references.

Now, in your case, Collections.emptyList() returns an unmodifiable EMPTY list. This is actually always the same instance since it is immutable and always empty. You cannot add to it because of the rule that an immutable list cannot be expanded (added to). Since it is empty there is also nothing in it that can be changed.

I should add to make it even more clear that Collection.emptyList() does not create an empty list. It just returns a reference to a singleton list instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM