当前位置: 动力学知识库 > 问答 > 编程问答 >

java - 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

网友答案:
  • 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
网友答案:

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

网友答案:

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.

网友答案:
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

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

分享给朋友:
您可能感兴趣的文章:
随机阅读: