Original URL: http://canofy.iteye.com/blog/258790
Java deep copy and shallow copy
- Shallow copy and deep copy
- //Shallow copy: All variables of the copied object contain the same value as the original object, and all references to other objects still point to the original object.
- //In other words, shallow copy simply duplicates the object being considered, not the object it refers to.
- //Deep copy: All the variables of the copied object contain the same values as the original object, removing those variables that refer to other objects.
- The variables that refer to other objects will point to new objects that have been copied, not those that are already referenced.
- //In other words, deep copy copies the objects that are referenced by the object being copied again.
- ///1, Direct Assignment (outside the string is a shallow copy)
- //2, using the constructor (deep copy)
- //3, using the Clone () method (deep copy)
- //String (not understood without Colne () method)
- String s="SSS";
- String T=s; //Deep copy
- String y=new string (s); //Deep copy
- System.out.println ("s:" +s+"T:" +t+"y:" +y ");
- t="TTT";
- y="yyy";
- System.out.println ("s:" +s+"T:" +t+"y:" +y ");
- //Array
- String[] ss={"111","222","333"};
- String[] TT=SS; //Shallow copy
- String[] ww= (string[]) ss.clone (); //Deep copy
- System.out.println ("ss:" +ss[1]+"tt:" +tt[1]+"ww:" +ww[1]);
- tt[1]="2t2";
- ww[1]="2w2";
- System.out.println ("ss:" +ss[1]+"tt:" +tt[1]+"ww:" +ww[1]);
- //list List
- ArrayList a=New ArrayList ();
- For (int i=0;i<10;i++) {
- A.add (string.valueof (i+1));
- }
- ArrayList B=a; //Shallow copy
- ArrayList c=New ArrayList (a); Deep copy
- ArrayList d= (ArrayList) A.clone (); //Deep copy
- System.out.println ("A:" +a.get (1) +"B:" +b.get (1) +"C:" +c.get (1) +"D:" +d.get (1));
- B.set (1, "BBB");
- C.set (1, "CCC");
- System.out.println ("A:" +a.get (1) +"B:" +b.get (1) +"C:" +c.get (1) +"D:" +d.get (1));
- //hashmap
- HashMap h=New HashMap ();
- H.put ("1", "HHH");
- HashMap m=h; //Shallow copy
- HashMap p=New HashMap (h); Deep copy
- HashMap n= (HASHMAP) H.clone (); //Deep copy
- System.out.println ("H:" +h.get ("1") +"M:" +m.get ("1") +"P:" +p.get ("1") + "N:" +n.get ( "1"));
- M.put ("1", "MMM");
- P.put ("1","PPP");
- N.put ("1", "nnn");
- System.out.println ("H:" +h.get ("1") +"M:" +m.get ("1") +"P:" +p.get ("1") + "N:" +n.get ( "1"));
"Turn" hashmap shallow copy and deep copy--good