我遇到它簡化到像這樣的一個問題:爲什麼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
第二次打印?
我覺得我誤解了引用是如何工作的,所以有人可以解釋爲什麼第一個示例中的臨時列表和原始列表一起受到影響,而臨時整數和原始整數給出與第二個示例中不同的結果?