"Go" Java How to Clone collections--deep copy ArrayList and HashSet

Source: Internet
Author: User
Tags addall shallow copy

Original URL: http://blog.csdn.net/cool_sti/article/details/21658521

Original English Link: http://javarevisited.blogspot.hk/2014/03/how-to-clone-collection-in-java-deep-copy-vs-shallow.html

Programmers often misuse copy constructors or other methods provided by collection classes (such as list, Set, ArrayList, HashSet) to complete a copy of the collection. It is worth remembering that the copy constructor provided by the collection in Java supports only shallow copies rather than deep copies, which means that objects stored in the original list and clone list remain consistent and point to the same memory address in the Java heap. The reason for this misunderstanding is that it uses collections to make a shallow copy of an immutable object, because the object is immutable, and it is reasonable that two sets point to the same object. It is so, so save the string in the pool, update one of them without affecting other objects. The problem is that when we use the copy constructor of ArrayList to create a clone of the Employee object list, where the employee object is mutable, in this case, if the original collection modifies one of the employee, the change also occurs in the collection of copies, But that's not what we want. In almost all cases, cloning should be independent of the original object. The way to avoid this problem is to use a deep copy collection that recursively copies the object until it accesses a primitive or immutable object. In this article, we will describe a method for deep copy collections, such as ArrayList or HashSet in Java. By the way, if you understand the difference between a shallow copy and a deep copy, you will easily grasp the mechanism of the deep copy collection. Deep copy in Java collection in the following example, we have a collection of variable employee objects, each containing the name and designation fields, and saving them in HashSet. We use the AddAll () method in the Java.util.Collection interface to create a copy of this collection. After that, we modify the designation field of each employee object in the original collection, hoping that the change will not affect the Copy collection, but that the solution to this problem is to deeply copy the elements in the collection class. [Java]View Plaincopy
  1. Import java.util.Collection;
  2. Import Java.util.HashSet;
  3. Import Java.util.Iterator;
  4. Import Org.slf4j.Logger;
  5. Import Org.slf4j.LoggerFactory;
  6. /**
  7. * Java program to demonstrate copy constructor of Collection provides shallow
  8. * Copy and techniques to deep clone Collection by iterating over them.
  9. * @author http://javarevisited.blogspot.com
  10. */
  11. Public class Collectioncloningtest {
  12. private static final Logger Logger = Loggerfactory.getlogger (Collectioncloningclass);
  13. public static void Main (String args[]) {
  14. //Deep cloning Collection in Java
  15. Collection org = new HashSet ();
  16. Org.add (new Employee ("Joe", "Manager"));
  17. Org.add (new Employee ("Tim", "Developer"));
  18. Org.add (new Employee ("Frank", " Developer"));
  19. //Creating copy of Collection using copy constructor
  20. Collection copy = new HashSet (org);
  21. Logger.debug ("Original Collection {}", org);
  22. Logger.debug ("copy of Collection {}", copy);
  23. Iterator ITR = Org.iterator ();
  24. While (Itr.hasnext ()) {
  25. Itr.next (). Setdesignation ("staff");
  26. }
  27. Logger.debug ("Original Collection after modification {}", org);
  28. Logger.debug ("copy of Collection without modification {}", copy);
  29. //Deep cloning List in Java
  30. }
  31. }
  32. Class Employee {
  33. private String name;
  34. private String designation;
  35. Public Employee (string name, string designation) {
  36. this.name = name;   this.designation = designation;
  37. }
  38. Public String getdesignation () {
  39. return designation;
  40. }
  41. public void Setdesignation (String designation) {
  42. this.designation = designation;
  43. }
  44. Public String GetName () {
  45. return name;
  46. }
  47. public void SetName (String name) {
  48. this.name = name;
  49. }
  50. @Override public String toString () {
  51. return String.Format ("%s:%s", name, designation);
  52. }
  53. }
Output: [HTML]View Plaincopy
    1. -Original Collection [Joe:manager, Frank:developer, Tim:developer]
    2. -Copy of Collection [Joe:manager, Frank:developer, Tim:developer]
    3. -Original Collection after modification [Joe:staff, Frank:staff, Tim:staff]
    4. -Copy of Collection without modification [Joe:staff, Frank:staff, Tim:staff]
It is clear that the employee object that modifies the original collection (that is, the Modify designation field is "Staff") is also reflected in the Copy collection, because the clone is a shallow copy that points to the same employee object in the heap. To fix this problem, we need to iterate through the set depth copy of all the employee objects, and before that we need to overwrite the Clone method for the Employee object. 1) Let the employee class implement the Cloneable interface, 2) Add the following clone () method to the employee class; [Java]View Plaincopy
  1. @Override
  2. Protected Employee Clone () {
  3. Employee clone = null;
  4. try{
  5. Clone = (Employee) super.clone ();
  6. }catch (Clonenotsupportedexception e) {
  7. throw New RuntimeException (e); //won ' t happen
  8. }
  9. return clone;
  10. }
3) Use the following code to replace the copy constructor with a deep copy in Java; [Java]View Plaincopy
    1. collection<employee> copy = new Hashset<employee> (Org.size ());
    2. iterator<employee> Iterator = Org.iterator ();
    3. while (Iterator.hasnext ()) {
    4. Copy.add (Iterator.next (). Clone ());
    5. }
4) Run the same code for the modified collection, and you will get different output: [HTML]View Plaincopy
    1. -Original Collection after modification [Joe:staff, Tim:staff, Frank:staff]
    2. -Copy of Collection without modification [Frank:developer, Joe:manager, Tim:developer]
It can be seen that the clone and the original set are independent of each other, pointing to different objects respectively. This is how Java clones all the contents of a collection, and now we understand that the various copy constructors in the collection class, such as the AddAll () method in list or set, implement only a shallow copy of the collection, that is, the collection of the original collection and the copy point to the same object. This also requires that any objects be stored in the collection, and deep copy operations must be supported. PS: The code execution in the original blog may encounter some problems, but the key is that the middle thought is very important. Links: How to create immutable Class and Object in java-tutorial exampledifference between deep copy vs Shadow cloning in Ja Vacollection Interview Questions Answershow Clone method works in Java

"Go" Java How to Clone collections--deep copy ArrayList and HashSet

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.