In Java, if you have the following code, list1 and list2 end up pointing to the same object, so a change in list2 will result in a change in list1.
ArrayList<Integer> list1 = new ArrayList<Integer>();
list1.add(1);
list1.add(2);
list1.add(3);
ArrayList<Integer> list2 = new ArrayList<Integer>();
list2 = list1;
list2.set(0, 10);
for(int i =0; i<list1.size(); i++){
System.out.println(list1.get(i));
}
for(int i =0; i<list2.size(); i++){
System.out.println(list2.get(i));
}
And the output ends up being:
10
2
3
10
2
3
However, in C++, the behavior is different?
vector<int> list1;
list1.push_back(1);
list1.push_back(2);
list1.push_back(3);
vector<int> list2;
list2 = list1;
list2.at(0) = 10;
for(int i =0; i<list1.size(); i++){
cout << list1[i] << endl;
}
for(int i=0; i<list2.size(); i++){
cout << list2[i] << endl;
}
The output ends up being:
1
2
3
10
2
3
Can someone explain?