jameshelou
jameshelou

Reputation: 95

Java - Confused with object assignment

the program

I have been following the Lynda.com java tutorials for the last few days now and I am quite confused by this one part in particular involving the line:

p1 = new Property(230000, "Estate", 2.0, 2, 3)

I have added p1 to the ArrayList mls twice now but when I make the Property p1 object equal a new object of the Property class, what exactly is happening here?

Am I changing the initial value of p1 or creating a new object from the 'object p1'?

Upvotes: 2

Views: 319

Answers (3)

Soumitri Pattnaik
Soumitri Pattnaik

Reputation: 3556

When you do p1 = new Property(230000, "Estate", 2.0, 2, 3) a new Property object is created in memory and it's reference is set in the p1 variable.

Let's say the pointer location is 100. So when you do arrayList.add(p1); 100 is added to the list.

Now when you change p1 by another new now the reference got changed to point the new object. Let's the pointer is 200. So the arraylist now has 200 and 100.

In this case even if, the actual reference variable p1 has lost the old object reference, but the list has both references 100 and 200. So it will have both the values.

Note : ArrayList allows duplicate insertion.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86774

You are creating a new instance of the class Property and setting the variable p1 to refer to it.

In your example code, the variable p1 is being re-used. First it points to the first created object, then that reference is stored in the ArrayList and p1 gets a new value (a reference to the second object). Then that second object reference is also stored in the ArrayList

Upvotes: 0

Chris Kitching
Chris Kitching

Reputation: 2655

Object variables in Java are always references.

Property p1 = new Property(230000, "Estate", 2.0, 2, 3)

This allocated a new Property object on the heap and set p1 to a reference to it.

p1 = some_other_property;

This made p1 now a reference to the same Property referenced by the variable some_other_property. We copied the reference.

someFunction(p1)

This copied the reference p1 into the argument of someFunction. Notice that none of this manipulation of the reference actually changed the Property object, we just mucked about with references to it.

This also means that you can have multiple references that point to the same underlying object. If you add p1 to an ArrayList twice, then do an operation that mutates the object, both entries in the ArrayList will reflect the change (as both refer to the same thing)

This question provides some related and interesting details:

Is Java "pass-by-reference" or "pass-by-value"?

Upvotes: 2

Related Questions