Reputation: 21319
What is the difference between the two :
hashMap_2 = hashMap_1;
and
hashMap_2 = new HashMap<Object_1,Object_2>(hashMap_1);
Is there any difference between the two ?
Accoriding to me both initializes a new HashMap
named hashMap_2
Upvotes: 1
Views: 150
Reputation: 5521
As every one said
hashMap_2 = hashMap_1; -->asssigns reference of HashMap1 to hashMap_2
and
hashMap_2 = new HashMap(hashMap_1); -->causes another hashmap to be created.
Adding below point
In both the cases the Object stored in the hashmap2 and hashMap_1 will be the same. Both will not do deep clonning
Upvotes: 0
Reputation: 872
1.hashMap_2 = hashMap_1;
hashMap_1 values has been assigned to hashMap_2
2.hashMap_2 = new HashMap<Object_1,Object_2>(hashMap_1);
new HashMap object(hashMap_2) was created
The differnce for both experssion is Assignment and Intialization
Upvotes: 1
Reputation: 41935
This statement hashMap_2 = hashMap_1;
is called reference assignment, where same object is referred by two reference variables.
When initializing a Object
then it comes with a new
operator, except primitives. Initialization process creates a new object on heap, whereas assignment does not create a new object.
Upvotes: 1
Reputation: 13556
hashMap_2 = hashMap_1;
means that both variables
refer to same object. hashMap_2
will now refer to the object being referred by hashMap_1
.hashMap_2 = new HashMap<Object_1,Object_2>(hashMap_1);
causes another hashmap to be
created with the values of hashMap_1
. HashMap
objects and they will have same valuesUpvotes: 13
Reputation: 517
First expression doesn't initialize a HashMap. Its just assigning the reference.
Upvotes: 4