I have this:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class ListTest {
public static void main(String[] args) {
String[] values = { "yes", "no"};
List<String> aa = Arrays.asList(values);
System.out.println(aa.getClass().getName());
aa.remove(0);
}
}
It gives:
$ java ListTest
java.util.Arrays$ArrayList
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)
at ListTest.main(ListTest.java:12)
Question: I understand why I am getting this exception. It is because the ArrayList
class from inside Arrays.java
is being used which does not have a remove()
method. My question is how can someone(any user, like me) know before using that the List
they received that it does not contain a remove
method?
I think it would result in reordering of the elements though. This UnsupportedOperationException comes when you try to perform some operation on collection where its not allowed and in your case, When you call Arrays.asList it does not return a java.util.ArrayList. It returns a java.util.Arrays$ArrayList which is an immutable list.
java.lang.UnsupportedOperationException The main reason behind the occurrence of this error is the asList method of java.util.Arrays class returns an object of an ArrayList which is nested inside the class java.util.Arrays. ArrayList extends java.util.AbstractList and it does not implement add or remove method.
And because an array is not resizeable, remove and add operation must be unsupported. The issue is you're creating a List using Arrays.asList () method with fixed Length meaning that Since the returned List is a fixed-size List, we can’t add/remove elements.
There is no way to know. All of the List<T>
methods that change the list are listed as optional. A subclass can implement them or not. Unfortunately the API does not include a method like isReadOnly()
, so there's no way to check if these methods will throw exceptions without calling them.
It is the responsibility of the owner of the read-only list not to pass it to methods that will try to change it.
As long as the Interface is properly implemented, writing a remove method that throws an Exception is completely legal. So, no you won't know until it breaks... That is when Javadoc comes handy.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With