我定义了静态最终ArrayList,然后将其发送到其他类进行更改。但它应该只在第二类中局部改变,因为他是最终的,就像我的例子中的 int 一样。为什么主类也发生了变化?
小代码示例:
public class Main {
private static final ArrayList<String> myList = new ArrayList<>(Arrays.asList("One", "Two"));
private static final int num = 5;
public static void main(String[] args) {
SecondClass second = new SecondClass(myList,num);
System.out.println("List in Main: "+myList.get(0));
System.out.println("Num in Main: "+num);
}
}
public class SecondClass {
public SecondClass(ArrayList<String> list, int num)
{
list.set(0,"Three");
num = 10;
System.out.println("List in second: "+list.get(0));
System.out.println("Num in Second: "+num);
}
}
我的输出:
List in second: Three
Num in Second: 10
List in Main: Three
Num in Main: 5
我期望的结果是:
List in second: Three
Num in Second: 10
List in Main: One
Num in Main: 5
最佳答案
myList
是不可变的;它指向的对象不是。如果您希望列表的内容不可变,请使用 Collections.unmodifyingList()
(或类似 Guava 的 ImmutableList
)。
(在方法签名中使用 ArrayList
是一种不好的形式。如果您真的有一个,只需使用 List
或 RandomAccessList
有充分的理由需要这种行为[你不需要]。)
关于java - 最终静态数组列表在函数中发生了变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44615642/