UnsupportedOperationException While Removing Element from List
While attempting to remove an element from a list using List.remove(), you may encounter an UnsupportedOperationException. This error arises when you call remove() on a list that does not support structural modifications, such as modifications that alter its size.
In the given code, you create a list using Arrays.asList(split), which returns a fixed-size list backed by the array split. Fixed-size lists do not allow you to add or remove elements, leading to the UnsupportedOperationException when you call remove().
To fix this issue, you can use a LinkedList instead. LinkedList supports efficient element removal and returns a list that can be structurally modified. Here's the corrected code:
List<String> list = new LinkedList<>(Arrays.asList(split));
Additionally, the code uses template.split("|") to split the string template. However, "|" is a regex metacharacter, so you need to escape it as "|" for it to be treated as a literal character for splitting.
Lastly, consider using a more efficient algorithm by generating random distinct indices and using a list iterator to remove elements in a single pass. This will improve the time complexity to O(N) instead of the current O(N^2).
The above is the detailed content of Why Does `List.remove()` Throw an `UnsupportedOperationException`?. For more information, please follow other related articles on the PHP Chinese website!