Question

I have a hashmap in which i am putting a reference to an object.

     DateTest test100 = new DateTest("ABC",100); 
     dateTestMap.put(96, test100);

I am passing this reference variable to a method where i am assigning it a different object and after returning i am pointing the existing reference to the new object as follows:

    test100 = datePassingTest(test100);

    private DateTest datePassingTest(DateTest test100)
    {
        DateTest newTest = new DateTest("XYZ", 69);
        test100 = newTest;
        return test100;
    }

Well, test100 does get modified to point to the new object but the value stored in map isn't getting updated. Is there something i am missing ?

Thanks, Adithya

Was it helpful?

Solution 3

DateTest test100 = new DateTest("ABC",100); 
dateTestMap.put(96, test100);

Here a copy of reference (of test100) goes and sits into the dateTestMap which points to DateTest("ABC",100). Now a HashMap dateTestMap contains a new reference which points to the same object DateTest("ABC",100)

So it can be depicted something like this

enter image description here

Now when you do

test100 = datePassingTest(test100);

The outer test100 will point to new DateTest("XYZ", 69), but the copy reference present in dateTestMap still points to same DateTest("ABC",100) object.

enter image description here

Java is pass by value - which essentially means passing the copy of reference

OTHER TIPS

That is because test100 is not holding the reference of the object which was created using this new DateTest("ABC",100);. It now points to the object created by this new DateTest("XYZ", 69);.

If you had done something like test100.setSomething(150), then the change would have been reflected in the map. In this case, it won't as the test100 now refers a completely different object.

When you do

test100 = newTest

The only thing that is done is that test100 now references the same object as newTest. The object referenced by the original value of test100 is still present but only in the hashmap.

To do what you want, you should try

test100.setTime(newTest.getTime());

Thats because, you're putting the object inside the map and then modifying the object. Thus, the map would still hold the old object

 DateTest test100 = new DateTest("ABC",100); 
 dateTestMap.put(96, test100);           // entry/object added to map

 test100 = datePassingTest(test100);     // object updated

 dateTestMap.put(96, test100);           // map gets new object

// now the map contains the updated object but not the older one.

You are not modifying the object. You are just assigning.

Clear explanation in Language Specification JLS#4.301,

If two variables contain references to the same object, the state of the object can be modified using one variable's reference to the object, and then the altered state can be observed through the reference in the other variable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top