Home >Java >javaTutorial >Why Does Removing Elements from a List Throw an UnsupportedOperationException?

Why Does Removing Elements from a List Throw an UnsupportedOperationException?

Susan Sarandon
Susan SarandonOriginal
2024-12-30 21:51:10496browse

Why Does Removing Elements from a List Throw an UnsupportedOperationException?

UnsupportedOperationException: Removing Element from a List

When attempting to remove an element from a list using list.remove(index), you may encounter an UnsupportedOperationException. This error stems from the use of a fixed-size list returned by Arrays.asList().

Arrays.asList() Returns a Fixed-Size List

Arrays.asList() creates a list backed by the given array. This list is immutable and does not support structural modifications like adding or removing elements.

Fix:

To resolve this issue, use a mutable list implementation that allows removals. For instance, you can use a LinkedList.

List<String> list = new LinkedList<>(Arrays.asList(split));

Splitting with Regular Expressions

The split() method is used with regular expressions to split a string. The pipe character (|) is a regex metacharacter that should be escaped when used as a literal.

Fix:

To split on a literal pipe character, escape it using double backslashes.

template.split("\|")

Optimized Algorithm

Instead of repeatedly invoking remove(), consider a more efficient algorithm:

  1. Generate a random array of numbers within the range of 0 to list.size() - 1.
  2. Sort the numbers in ascending order.
  3. Create another list and iterate through list while iterating through the sorted numbers.
  4. When the index of the current number in the sorted list matches the index of the element in list, call remove() on list and remove the element.

This algorithm runs in O(N) time, where N is the size of the list, which is significantly faster than the original approach.

The above is the detailed content of Why Does Removing Elements from a List Throw an UnsupportedOperationException?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn