我遇到它简化到像这样的一个问题:为什么ArrayList副本的行为与整数副本不一样?
public static void main(String[] args) {
ArrayList<String> firstList = new ArrayList<>();
firstList.add("Hello");
firstList.add("World");
firstList.add("This");
firstList.add("Is");
firstList.add("A");
firstList.add("Test");
System.out.println("Size of firstList: " + firstList.size());
ArrayList<String> tempList = firstList;
System.out.println("Size of tempList: " + tempList.size());
firstList.clear();
System.out.println("Size of firstList: " + firstList.size()); // should be 0
System.out.println("Size of tempList: " + tempList.size());
}
,输出是:
Size of firstList: 6
Size of tempList: 6
Size of firstList: 0
Size of tempList: 0
我期望的tempList
第二次大小轮是6
而不是0
。
已经有一些与此效果有关的问题,如this one和another one。
从答案,我发现,这是因为tempList
是指同一基准firstList
所以当firstList
变化也是如此tempList
(纠正我,如果我错了这里)。
因此,一个更好的解决方案,这将是这样的:
ArrayList<String> tempList = new ArrayList<String>(firstList);
如果有关引用的上述信息是真实的,那么,为什么这样的代码:
public static void main(String[] args) {
int firstValue = 5;
System.out.println("firstValue: " + firstValue);
int tempValue = firstValue;
System.out.println("tempValue: " + firstValue);
firstValue = 3;
System.out.println("firstValue: " + firstValue);
System.out.println("tempValue: " + tempValue);
}
给这个输出:
firstValue: 5
tempValue: 5
firstValue: 3
tempValue: 5
?
应该tempValue
不是也是3
第二次打印?
我觉得我误解了引用是如何工作的,所以有人可以解释为什么第一个示例中的临时列表和原始列表一起受到影响,而临时整数和原始整数给出与第二个示例中不同的结果?