Harshveer Singh
Harshveer Singh

Reputation: 4187

Can I change objects in one ArrayList using references in another one?

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

Answers (3)

Elias M&#229;rtenson
Elias M&#229;rtenson

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

Saeed
Saeed

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

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

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

Related Questions