3

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.

1
  • 6
    Wouldn't it have been easier just to try it and find out? Commented Aug 15, 2011 at 8:25

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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"

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.