Consider, that I have a driver function foo()
which is defined as follows:
void foo()
{
Map<Integer,Character> map = new HashMap<Integer,Character>() ;
bar(map)
//operations on map
}
void bar(Map<Integer,Character> map)
{
Map<Integer,Character> map2 = new HashMap<Integer,Character>(map) ;
//operations over map2
}
Now, according to what I know, the operations on map2
should change the original map
, and therefore operations on map
inside foo()
would be on a different version of map
than the original one.
Reason for my belief:
- According to this post, we can say that we're making a shallow copy of the Hash Map.
- In this documentation, in which it is clearly said that:
Reference data type parameters, such as objects, are also passed into methods by value. This means that when the method returns, the passed-in reference still references the same object as before. However, the values of the object's fields can be changed in the method, if they have the proper access level.
Therefore, since we're making a shallow copy, operations over the copy will ultimately change the passed map, and all the changes over this passed map are reflected over the original map, due to point 2.
But I've got a contradictory example that questions my understanding. So, is my thinking correct? Or there is something else to it?