java - 为什么我的列表在我更改创建它的数组时被修改

标签 java collections

<分区>

import java.util.*;

public class Test {
    public static void main(String[] args) {
        String[] arr = {"Java", "Champ", "."};
        List<String> list = (List<String>) Arrays.asList(arr); // line 1
        arr[2] = ".com"; // line 2
        for (String word : list) {
            System.out.print(word);
        }
    }
}

有人可以解释一下为什么我们会来到这里“JavaChamp.com”吗? 我认为它应该只是“JavaChamp”。因为第 2 行在第 1 行之后。

最佳答案

因为 Arrays#asList返回由数组支持的固定大小的 List

这是 Arrays#asList 的文档:

Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.

关于java - 为什么我的列表在我更改创建它的数组时被修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58328564/

相关文章:

线程 "WindowsNativeRunloopThread"java.lang.NoSuchMethodError : <init> 中的 JavaFX 异常

java - 有没有办法获取在 JVM 中运行的所有 Spring 应用程序上下文的列表?

c# - 无需强制转换即可保存不同类型的阻塞集合的字典

java - 重复的对象被添加到列表中

python - 在 Python 中创建唯一对象数组

java - 总和为 N 且逆数总和为 1 的所有自然数

java - 在java中打开新的动态Web项目

java - 使用 CardLayout 将自定义面板添加到 Applet

.net - 为什么 ReadOnlyCollection<T> 不是 ReadOnlyList<T>?

go - golang 中的集合