40

Possible Duplicate:
Is Java pass-by-reference?

Does a List object get passed by reference? In other words, if I pass an ArrayList (java.util.ArrayList) object to a class, will it be automatically updated when I change it?

Community
  • 1
  • 1
Kirill Kulakov
  • 10,035
  • 9
  • 50
  • 67
  • 1
    Hint: `ArrayList` or `List` is not special in this regard. In fact **no class** is special in this regard. – Joachim Sauer Jul 09 '12 at 14:25
  • 2
    All primitives and references are *passed by value* in Java. In your case you have a reference to a List (not a List as such) and the reference to it will be passed by value. – Peter Lawrey Jul 09 '12 at 14:32

4 Answers4

41

in other word: If I pass an ArrayList (java.util.ArrayList) object to a class, will it be automatically updated when I change it?

Yes

Does the List object passed by reference?

Value of reference would get passed

public updateList(List<String> names){
 //..
}

Explanation

When you call updateList(someOtherList); the value of someOtherList which is a reference will copied to names (another reference in method, bit by bit) so now both of them are referring to same instance in memory and thus it will change


See

Community
  • 1
  • 1
jmj
  • 237,923
  • 42
  • 401
  • 438
19

Yes, a List that you pass to a method is passed by reference. Any objects you add to the List inside the method will still be in the List after the method returns.

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
7

If you add to a list in one method, its original reference in first method will also contain the new item.

java is pass by value, and for objects this means the reference is passed by value.

Community
  • 1
  • 1
NimChimpsky
  • 46,453
  • 60
  • 198
  • 311
0

Yes, because You just pass a reference of ArrayList-Object, to your Object.

lhlmgr
  • 2,087
  • 1
  • 22
  • 38