虽然可以从Arrays.asList ()生成List,但请注意,从Arrays.asList生成的List基于固定大小的数组,并且仅支持不更改数组大小的操作。 所以,为了不发生意想不到的错误,我们必须时刻记住。

如果希望通过将在Arrays.asList中获得的List作为构造函数的参数传递给ArrayList或使用addAll方法添加来获得可操作的List。

示例:

import java.util.AbstractList;

import java.util.AbstractMap;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collection;

import java.util.Collections;

import java.util.List;

import java.util.Map;

import java.util.Set;

公共类测试{

publicstaticvoidtest (字符串msg,列表列表) {

计算c=列表;

collection sublist=list.sublist (1,3 );

collection C2=new ArrayList (子列表;

system.out.println (—- ‘ msg ‘—- ) );

try{

c .移除全部(C2;

}catch(exceptione ) {

system.out.println (移动全部: ) e;

}

try{

c .返回全部(C2;

}catch(exceptione ) {

system.out.println (retain all : ) e;

}

try{

c.clear (;

}catch(exceptione ) {

system.out.println(clear: ) e;

}

try{

c .添加(XXX );

}catch(exceptione ) {

系统. out.println (add : ) e;

}

try{

c.addall(C2;

}catch(exceptione ) {

system.out.println(addall: ) e;

}

try{

c .移除(x );

}catch(exceptione ) {

系统. out.println (remove : ) e;

}

try{

list.set(0,’ XYZ ‘;

}catch(exceptione ) {

system.out.println (list.set : ) e;

}

}

publicstaticvoidmain (字符串[ ] args ) {

list list=arrays.as list (abcdefghbihikhkigg ‘.split );

测试(modifiable1)、新阵列(newArraylist ) )列表;

列表列表2=new ArrayList (;

list2.addall(list;

测试(modifiable2)、列表2 );

collections.addall(list2,’ A B C D E F G H B I HIK HKI GG’.split (‘ ‘ );

测试(modifiable3)、列表2 );

test(Arrays.aslist )、list );

test(unmodifiablelist (,collections.unmodifiablelist ),list );

}

}

输出:

——- modifiable1——— –

— -修改2—-

— -修改3—-

——arrays.as list——– –

remove all : Java.lang.unsupportedoperationexception

retain all : Java.lang.unsupportedoperationexception

clear : Java.lang.unsupportedoperationexception

add : Java.lang.unsupportedoperationexception

addall : Java.lang.unsupportedoperationexception

——- unmodifiablelist———————————————-。

remove all : Java.lang.unsupportedoperationexception

retain all : Java.lang.unsupportedoperationexception

clear : Java.lang.unsupportedoperationexception

add : Java.lang.unsupportedoperationexception

addall : Java.lang.unsupportedoperationexception

remove : Java.lang.unsupportedoperationexception

list.set : Java.lang.unsupportedoperationexception