Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 611
Ankur Agarwal Avatar asked Sep 26 '14 05:09

Ankur Agarwal


People also ask

What does unsupportedoperationexception mean in ArrayList?

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.

Why does aslist return unsupportedoperationexception in Java?

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.

Why can’t I add/remove elements from a list in Java?

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.


2 Answers

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.

like image 145
John Kugelman Avatar answered Sep 21 '22 19:09

John Kugelman


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.

like image 43
Desorder Avatar answered Sep 22 '22 19:09

Desorder