File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes clone() - shallow or deep? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "clone() - shallow or deep?" Watch "clone() - shallow or deep?" New topic
Author

clone() - shallow or deep?

David Duran
Ranch Hand

Joined: Feb 11, 2002
Posts: 122
According to the HashMap javadoc, the clone() method does a shallow copy only, the keys and values are not cloned. If that is the case, why is it that the key in the cloned object below is maintained:

The result is: null, world
If the keys and values were not supposed to be cloned, then shouldn't the result be: null, null?
Thomas Paul
mister krabs
Ranch Hand

Joined: May 05, 2000
Posts: 13974
A shallow copy means the HashMap has been copied but not the objects in the HashMap. So adding and removing from one HashMap does not cause changes to the clone. Try this. Create a Button and set it's text to "OK". Put the Button in a HashMap. Clone the HashMap. Change the Button's text in one HashMap to "Cancel". Compare the text of Button in each HashMap. What do you think you will find?


Associate Instructor - Hofstra University
Amazon Top 750 reviewer - Blog - Unresolved References - Book Review Blog
 
IntelliJ Java IDE
 
subject: clone() - shallow or deep?
 
Threads others viewed
Cloneable vs. copy constructor
clone() used on array and object
convert "forty five" to "45"
Question about clone a Hashtable
Cloning a Hashtable
WebSphere development made easy
without the weight of IBM tools
http://www.myeclipseide.com