Originally posted by Sumit Bansal:
HashMap h1 = new HashMap();
h1.put("one", "one");
h1.put("two", "two");
h1.put("three", "three");
h1.put("four", "four");
h1.put("five", "five");
HashMap h2 = null;
1)//h2 = h1; // Assign reference directly
2)h2 = (HashMap)h1.clone(); // make a clone of the object
h1 = null;
If you try option (1) or (2), both gives the same result, i have tried it. then what is the difference between these two ways [except clone() instantiate a new object with same values]?
Also which one is more efficient and right to use?
When more than one reference are referring same object (not an immutable one), change made through one reference is reflected through any other.
If my father destroys his house, I will also have my house destroyed; because we are under same roof.