This question already has answers here:
what is the sense of final ArrayList?
(12个答案)
2年前关闭。
我定义了静态最终ArrayList,然后将其发送到其他类进行更改。但由于他是决赛选手,因此应该仅在第二类中局部更改,例如在我的示例中为int。为什么在Main Class中也更改了?
小代码示例:
我的输出:
我期望的是:
(12个答案)
2年前关闭。
我定义了静态最终ArrayList,然后将其发送到其他类进行更改。但由于他是决赛选手,因此应该仅在第二类中局部更改,例如在我的示例中为int。为什么在Main Class中也更改了?
小代码示例:
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.unmodifiableList()
(或类似Guava的ImmutableList
之类的东西)。
(而且在方法签名中使用ArrayList
是一种不好的形式。如果确实有充分的理由需要使用[cc],则请使用List
或RandomAccessList
。)