Arrays.asList()陷阱

public class ArrayASListTest
{
     public static void main(String[] args)
    {
          /*
          String[] s = new String[]{"one","two"};
          List wrongList = Arrays.asList(s); 
          wrongList.remove(0);
          */
        

        String[] s = new String[]{"one","two"};
        List rightList = new ArrayList(Arrays.asList(s)); 
        wrongList.remove(0); 
   }
}

 

Arrays.asList()生成的List是java.util.Arrays$ArrayList,它的remove和add实现就是抛出UnsupportedOperationException异常。

 

改正方法也很简单,换成ArrayList或者LinkedList就可以了

你可能感兴趣的:(java点点滴滴)