I've come across a problem which simplifies down to something like this:
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());
}
And the output is:
Size of firstList: 6
Size of tempList: 6
Size of firstList: 0
Size of tempList: 0
I would expect the size of tempList
the second time round to be 6
instead of 0
.
There have already been some questions relating to this effect such as this one and another one.
From the answers, I've found that this is because tempList
refers to the same reference as firstList
so when firstList
changes so does tempList
(correct me if I'm wrong here).
So a better solution to this would be something like:
ArrayList<String> tempList = new ArrayList<String>(firstList);
If the information about references mentioned above is true, then why does this code:
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);
}
give this output:
firstValue: 5
tempValue: 5
firstValue: 3
tempValue: 5
?
Should tempValue
not also be 3
the second time it is printed?
I feel like I'm misunderstanding how references work, so could someone explain why the temporary list and original list in the first example are affected together, whereas the temporary integer and original integer give different results as in the second example?