saplingPro
saplingPro

Reputation: 21319

What is the difference between these two ways of initializing a HashMap?

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

Answers (5)

upog
upog

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

Yellow Flash
Yellow Flash

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

Narendra Pathai
Narendra Pathai

Reputation: 41935

ASSIGNMENT

This statement hashMap_2 = hashMap_1; is called reference assignment, where same object is referred by two reference variables.

INITIALIZING

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

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

  • The statement hashMap_2 = hashMap_1; means that both variables refer to same object.
  • The variable hashMap_2 will now refer to the object being referred by hashMap_1.
  • This means only one object will be there but two variables referring to same object.
  • The statement hashMap_2 = new HashMap<Object_1,Object_2>(hashMap_1); causes another hashmap to be created with the values of hashMap_1.
  • There will be two different HashMap objects and they will have same values

Upvotes: 13

hanish.kh
hanish.kh

Reputation: 517

First expression doesn't initialize a HashMap. Its just assigning the reference.

Upvotes: 4

Related Questions