java.lang.UnsupportedOperationException at java.util.AbstractLis


今日コードを書いて簡略化した後、以下のように問題のエラーが発生しました.

  public void do(List rs){
    rs.remove("a");
  }

届いたrsがArrayListだったのを覚えているのに.
前のコードをよく調べた

    List rs =Arrays.asList(new String[]{"a","c"});
    do(rs);

javadocをよく調べて
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. You cannot add to it and you cannot remove from it.
If you want a mutable list built from your array you will have to loop over the array yourself and add each element into the list in turn.
Even then your code won't work because you'll get an IndexOutOfBoundsException as you remove the elements from the list in the for loop. There are two options: use an Iterator which allows you to remove from the list as you iterate over it (my recommendation as it makes the code easier to maintain) or loop backwards over the loop removing from the last one downwards (harder to read).
You are using AbstractList. ArrayList and Arrays$ArrayList are both types of AbstractList. That's why you get UnsupportedOperationException: Arrays$ArrayList does not override remove(int) so the method is called on the superclass, AbstractList, which is what is throwing the exception because this method is not implemented on that class (the reason being to allow you to build immutable subclasses)
解決策はサイクルadd()を用いることである.
またはArrayListに変換

List list = Arrays.asList(a[]);
List arrayList = new ArrayList(list);