Reputation: 4187
First array list:- ArrayList<Object> list1;
Second array list:- ArrayList<Object> list2;
Suppose I have filled list1
with some objects.
Now I copy some of objects from list1
using list2.add(list1[i])
and make change to object in list2
using list2[j].setA = something
.
Will the corresponding value A of object in list1 change or not?
Actually I want the value A
to be changed.
Upvotes: 3
Views: 5106
Reputation: 3885
A java.util.List
(which includes both ArrayList
and LinkedList
) contains references to objects. That is to say, that if you have a single instance of an object and put that instance in two lists, those two lists will reference the same actual object.
In fact, Java does not have "value objects" unlike some other languages do (i.e. C, C++ and C#). Neither variables nor arrays (and by consequence, any of the collection classes like List
) can ever contain objects. They can only contain references to objects.
Here's an example which uses variables to make the functionality clear:
Foo x = new Foo(); // Create a new instance of Foo and assign a reference to it to "x"
Foo y = x; // Copy the reference (not the actual object) to "y"
// At this point, both x and y points to the same object
x.setValue(1); // Set the value to 1
y.setValue(2); // Set the value to 2
System.out.println(x.getValue()); // prints "2"
Now, the exact same is true for lists as well:
List<Foo> listA = new ArrayList<Foo>();
List<Foo> listB = new ArrayList<Foo>();
listA.add(new Foo());
listB.add(listA.get(0));
// The single instance of Foo is now in both lists
listB.get(0).setValue(1);
System.out.println(listA.get(0).getValue()); // Prints "1"
Upvotes: 2
Reputation: 7370
Yes, It will change. In java, you work with the references of objects. so when you put an object in a list, you just put it's reference in list. when you copy it to the other list, you just copy the reference and when you change something, you are using a reference to change the original object. so your original object has been changed.
Upvotes: 0
Reputation: 116266
It will change. The lists contain only references to the objects*. So after adding some of the elements in list1
to list2
, the two lists will share references to the same physical objects.
*In Java collections you can't store primitive types such as int
, only their object counterparts (Integer
in this case), always by reference.
Upvotes: 10