1

For the following code:

User myUser = new User();
User[] array1 = new User[10];
User[] array2 = new User[10];
array1[5] = myUser;
array2[5] = myUser;

Is the object myUser stored twice, or is only the address of the object stored on each of the objects?

Also does this still hold if i start messing around with the variable like:

temp = myUser;
array2[4] = temp;

Also if i make a change to myUser in one array, does it make the change to the other array?

EDIT: last question how would one store it by value instead of reference?

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
  • possible duplicate of [Duplicating objects in Java](http://stackoverflow.com/questions/12072727/duplicating-objects-in-java) – Jason C Mar 06 '14 at 04:26

1 Answers1

4

Yes, only the reference to the User object is stored in the array. Each of the reference points to the same object. Modifying the object through either of the arrays will modify the same one object.

The same applies to storing the refernce in variables as in your second example.

Only primitive types are stored by value, e.g. int, boolean, char. Note that they also have corresponding reference type, e.g. for int you have Integer.

Szymon
  • 42,577
  • 16
  • 96
  • 114
  • Great so it only stored once. Last question how would one avoid this so that this dosen't happen. I.e. its stored by value instead – Yahya Uddin Mar 06 '14 at 04:26
  • The only things stored by value (in arrays and collections) are primitives: ints, booleans, chars, etc. – aliteralmind Mar 06 '14 at 04:27
  • You need to create a deep copy of the object to avoid it. – Szymon Mar 06 '14 at 04:27
  • @YahyaUddin You would have to manually create a deep copy of the object; specifics depend on the exact nature of the data in your object. Typical techniques include defining a constructor that takes another instance of your object and copies its values, and/or overriding `Object.clone()`. – Jason C Mar 06 '14 at 04:28
  • "Only primitive types are stored by value, e.g. int, boolean, char." Huh. I couldn't have said it better myself. – aliteralmind Mar 06 '14 at 04:31
  • @user2310289 No, not at all. You'd have to override `clone()` as a public method first, and decide which members deserved deep vs. shallow copies. You really should consider deleting that comment as without further explanation it's incredibly misleading advice. – Jason C Mar 06 '14 at 04:31
  • 1
    @JasonC I think your comment has enhanced my comment to that degree. – Scary Wombat Mar 06 '14 at 04:39
  • @user2310289 Huh. I guess it did, didn't it? – Jason C Mar 06 '14 at 04:49
  • You can also use Object.assign() for semi deep copy, it isn't a completely deep copy because it won't create a new copy for reference types in the object. You can also use Object.create(). However Object.create puts it in the prototype – Braden Brown Jun 29 '18 at 21:20
  • Yeah this screwed up a code I had, and I was wondering what happened. – Yolomep Oct 17 '20 at 01:39