When attempting to modify an existing list with the add() method in Java, you might occasionally encounter an UnsupportedOperationException. This issue arises due to the fact that not all List implementations provide support for adding or removing elements.
One common scenario where this error occurs is when using the Arrays.asList() method. The list returned by Arrays.asList() is immutable, meaning it does not allow structural modifications, including adding or removing elements. The documentation for Arrays.asList() explicitly states that it creates a "fixed-size list backed by the specified array."
<code class="java">List<String> membersList = Arrays.asList(membersArray); seeAlso.add(groupDn); // UnsupportedOperationException</code>
To resolve this, you can either create a copy of the list using a mutable implementation like ArrayList, or verify that the specific List implementation you're using supports the add() operation.
<code class="java">seeAlso = new ArrayList<>(seeAlso); // Corrected code</code>
The above is the detailed content of Why am I getting an UnsupportedOperationException when using Java List.add()?. For more information, please follow other related articles on the PHP Chinese website!