Home >Java >javaTutorial >Why Does Removing Elements from Arrays.asList() Throw an UnsupportedOperationException?
Arrays.asList() Convenience: Pitfalls Revealed
Arrays.asList() offers a simplistic approach to creating a List, but it comes with a caveat – its elements are immutable. Attempting to perform operations like remove() triggers an UnsupportedOperationException.
Arrays.asList() generates a "fixed-size list," prohibiting any structural modifications, including element removal.
To address this limitation, opt for a LinkedList, renowned for its swift remove() operation:
List<String> list = new LinkedList<String>(Arrays.asList(split));
When employing String.split() to partition a string, bear in mind that the pipe character (|) holds significance as a regex metacharacter. To avoid confusion, enclose it within backslashes (|) for a literal match:
template.split("\|")
To overcome the inefficiency of step-by-step element removal, leverage a more efficient approach:
This refined approach boasts an O(N) complexity, assuring optimal performance.
The above is the detailed content of Why Does Removing Elements from Arrays.asList() Throw an UnsupportedOperationException?. For more information, please follow other related articles on the PHP Chinese website!