当我们使用java.util.Arrays.asList()从数组创建列表时,该列表是可变的。
是和否:可以通过调用来修改列表
list.set(index, element);
但列表可能 不会 进行 结构
修饰。这意味着不可能将元素添加到列表中或从列表中删除元素。原因很简单,因为列表仍受数组支持,并且数组的大小可能不会更改。
当我们需要固定大小的可变集合时,我们选择数组
这就是关键点这里:数组是 不是
一个集合。该
Arrays.asList方法主要充当“数组世界”和“集合世界”之间的“桥梁”。
Arrays.asList例如,该方法使您可以将数据传递给期望使用的方法
Collection:
// A method that expects a collection:void process(List<String> strings) { ... }void call(){ String array[] = new String[] { "A", "B", "C" }; // Pass the array (as a list) to the method: process(Arrays.asList(array));}该应用案例包括从数组创建其他集合。例如,如果您有一个数组并想创建一个
Set包含该数组中元素的数组,则可以
String array[] = new String[] { "A", "B", "C" };Set<String> set = new HashSet<String>();for (String s : array) { set.add(s);}但是使用该
Arrays.asList方法,可以更方便地完成此操作:
Set<String> set = new HashSet<String>(Arrays.asList(array));
Arrays.asList可以说该方法与Collection#toArray方法的对等方法相反,后者以相反的方向工作(尽管此方法通常涉及创建和填充
新 数组,而该
Arrays.asList方法只是“包装”一个数组并使它“看起来像” a
List)。



