-1

When we call ArrayList.add() method, does it create a new object and add it to the list or does it adds the referenced object to the list?

For example: suppose we have two ArrayList as follows:

ArrayList<ClassA> a1 and ArrayList<ClassA> a2. If I run the code:

a2.add(a1.get(i)) will it create a new object and then add it to a2 or it will refer to the same object from two different lists?

It is not the copy of

Is Java pass by value or pass by reference question?

because I want to know the internal working of ArrayList.add() method, that does it create an object copy of the parameter passed or not?

cnova
  • 685
  • 2
  • 8
  • 22
  • Possible duplicate of [Is Java "pass-by-reference" or "pass-by-value"?](http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Savior Apr 17 '16 at 19:26
  • @Pillar it's about how `ArrayList.add()` method works. – cnova Apr 17 '16 at 19:37
  • There's no reason to be specific about `add`. All methods work the same in this regard. – Savior Apr 17 '16 at 20:33
  • Its not about how add is taking in the parameter. It's about what it does with the parameter when it receives it, does it create an object copy (of the parameter passed) and then adds or does it use the same object (parameter passed) and then adds it to the list. Now I know the answer. – cnova Apr 17 '16 at 20:36
  • Yeah, that's exactly what the other question is asking about and what the answers explain. – Savior Apr 17 '16 at 20:37

3 Answers3

3

It will refer to the same object in two different lists.

Of course, you can always verify this with some debugging effort.

ChiefTwoPencils
  • 11,778
  • 8
  • 39
  • 65
2

You can only pass references or primitives to a method. This method is no exception.

 ArrayList<String> list = new ArrayList<>();
 String s = "Hello";
 list.add(s); // pass the reference.

a2.add(a1.get(i)) will it create a new object and then add it to a2 or it will refer to the same object from two different lists?

This will mean both Lists have a copy of the same reference (which will point to the same object)

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
2

It will refer to the same object from those two different lists, which means if you edit that object from one place, another also gets impacted.

If you dont want that, consider making that class immutable

Raman Shrivastava
  • 2,827
  • 12
  • 25