Search code examples
javalistunsupportedoperation

How to know if List.remove() is "Unsupported"?


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?


Solution

  • 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.