Arrays.asList(T... a)替代方法,异常:Exception in thread “main“ java.lang.UnsupportedOperationException

众所周知

Arrays.asList(T… a):

该方法返回定长的 List,不支持 add 和 remove 操作
该方法返回的 List 与传入数组是映射关系(视图):set/get 操作直接作用于数组;直接修改数组,list 也会改变

源码:

    */
    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

返回的是一个static 静态list,对list add,set 等操作会抛出异常:
Exception in thread “main” java.lang.UnsupportedOperationException
替代方案:

//直接声明 
List<String> list = new ArrayList<>(Arrays.asList("a", "b","c"));
//简介声明
String[] arr = {"a", "b", "c"};
List<String> list = new ArrayList<>(Arrays.asList(arr));
 
// 直接
List<String> list = Collections.addAll(list, "a", "b", "c");
//间接
String[] arr = {"a", "b", "c"};
List<String> list  = Collections.addAll(list, arr);
 
// 直接声明
List<String> list = Arrays.stream(new String[]{"a", "b","c"}).collect(Collectors.toList());
//间接
String[] arr = {"a", "b", "c"};
List<String> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
 
//直接声明
List<String> list = Lists.newArrayList("a","b", "c");
//间接声明
String[] arr = {"a", "b", "c"};
List<String> list = Lists.newArrayList(Ints.asList(arr));

你可能感兴趣的:(java)