What is the difference between the two :
hashMap_2 = hashMap_1;
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_2 = hashMap_1;means that both variables refer to same object.
hashMap_2will now refer to the object being referred by
hashMap_2 = new HashMap<Object_1,Object_2>(hashMap_1);causes another hashmap to be created with the values of
HashMapobjects and they will have same values
First expression doesn't initialize a HashMap. Its just assigning the reference.
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.
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
As every one said
hashMap_2 = hashMap_1; -->asssigns reference of HashMap1 to hashMap_2
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