java - 关于不可变列表(由 Arrays.asList() 创建)

标签 java arrays list collections immutablelist

当我们使用 java.util.Arrays.asList() 从数组创建列表时,列表是不可变的。我只是想知道当 List(或 SetMap)的基本目的是为了具有动态大小并能够随意添加、删除元素。当我们需要固定大小的数据结构时,我们选择 Array,当我们需要动态数据结构时,我们选择 ListSetMap 等.那么拥有不可变列表的目的是什么?我在完成作业时遇到了这个问题。

最佳答案

When we create a list from an array using java.util.Arrays.asList() , the list is mutable.

是和否:可以通过调用修改列表

list.set(index, element);

但该列表可能不会 在结构上 被修改。这意味着无法向列表添加元素或从列表中删除元素。原因很简单,列表仍然由数组支持,数组的大小可能不会改变。

When we need a fixed size mutable collection we go for Array

这就是这里的关键点:数组不是 Collection . 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方法只是“包装”一个数组并让它“看起来像”一个 List)。

关于java - 关于不可变列表(由 Arrays.asList() 创建),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25447502/

相关文章:

java - 为什么会发生此 ArrayIndexOutOfBounds 异常?

vb.net - VB : List(Of List(Of String)) keeps changing the content of the outer list when I change the inner one?

python - 文件类型列表声明问题

python - 如何在 Python 中打乱多维列表

java - 插件开发: create new file dialog using FileDialog

java - 什么是内容存储库中的工作空间?

c - 为什么数组指针的地址与该指针中存储的数据相同?

c++ - 从文件中读取并保存到数组c++

java - 用户在java中创建n个对象

java - 以多线程方式浏览Jms Queue