File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Collection issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Collection issue" Watch "Collection issue" New topic
Author

Collection issue

ravindra patil
Ranch Hand

Joined: Sep 01, 2006
Posts: 214
Wel

i am copying values from Hashmap to another Hashmap

Hashmap a = b;

as soon as i put some values in a it atuomatically updates values in b ..

i dont wannt that ..


Any tips on this ?

James Boswell
Bartender

Joined: Nov 09, 2011
Posts: 973
    
    5

Ravindra

This is happening because a and b refer to the same object.
dennis deems
Ranch Hand

Joined: Mar 12, 2011
Posts: 808
I would have to see your code to be sure, but if you really did write then you haven't made a copy, you've just created a second reference to the same object that b refers to.

Try this: instantiate a new Map, then call Map.putAll.
Jeff Verdegan
Bartender

Joined: Jan 03, 2004
Posts: 6109
    
    6

ravindra patil wrote:Wel

i am copying values from Hashmap to another Hashmap

Hashmap a = b;


That doesn't copy values from one Map to another.

Just like every other reference variable assignment in Java, all that does is make a copy of the reference, so now we have two references pointing to the same HashMap object.


as soon as i put some values in a it atuomatically updates values in b ..

i dont wannt that ..


Any tips on this ?



You need to actually copy the Map.

HashMap has a copy constructor. It's also Cloneable. Either one of those will work.

Note, however, that this is a shallow copy. You'll have two Maps, but the Maps' keys and values references will point to the same objects. So if you do a.put(x, y), it won't affect b, but if you do a.get(x).setY(z), then both Maps will see it, since they're referencing the same value object for the key x.
ravindra patil
Ranch Hand

Joined: Sep 01, 2006
Posts: 214
thanks for fast reply .. i will update on this ...

Rancher's Rocks !!!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection issue
 
Similar Threads
A dumb question
Accessing HashMaps
how hashmap identify the duplicate values? (i need internal logic)
iterate HashMap<String,List> in My jsp page
HashMap size