深层克隆

2014-11-23 23:19:08 · 作者: · 浏览: 0
1、表层克隆

  1. public class Snake implements Cloneable
  2. {
  3. private Snake next;
  4. private char c;
  5. Snake(int i, char x){
  6. c = x;
  7. if(--i > 0){
  8. next = new Snake(i,(char)(x+1));
  9. }
  10. }
  11. public void increment(){
  12. c++;
  13. if(next!=null){
  14. next.increment();
  15. }
  16. }
  17. public String toString(){
  18. String s = ":"+c;
  19. if(next!=null){
  20. s += next.toString();
  21. }
  22. return s;
  23. }
  24. public Object clone(){
  25. Object o = null;
  26. try{
  27. o = super.clone();
  28. }catch(CloneNotSupportedException e){}
  29. return o;
  30. }
  31. public static void main(String[] args)
  32. {
  33. Snake s = new Snake(5,a);
  34. System.out.println("s ="+s);
  35. Snake s2 = (Snake)s.clone();
  36. System.out.println("s2 ="+s2);
  37. s2.increment();
  38. System.out.println("after s2.increment, s="+s+" s2 ="+s2);
  39. }
  40. }

此时的输出结果:
s =:a:b:c:d:e
s2 =:a:b:c:d:e
after s2.increment, s=:a:c:d:e:f s2 =:b:c:d:e:f
2、深层克隆

  1. public class Snake implements Cloneable
  2. {
  3. private Snake next;
  4. private char c;
  5. Snake(int i, char x){
  6. c = x;
  7. if(--i > 0){
  8. next = new Snake(i,(char)(x+1));
  9. }
  10. }
  11. public void increment(){
  12. c++;
  13. if(next!=null){
  14. next.increment();
  15. }
  16. }
  17. public String toString(){
  18. String s = ":"+c;
  19. if(next!=null){
  20. s += next.toString();
  21. }
  22. return s;
  23. }
  24. public
    <script type="text/java script">BAIDU_CLB_fillSlot("771048");
    点击复制链接 与好友分享! 回本站首页
    <script> function copyToClipBoard(){ var clipBoardContent=document.title + '\r\n' + document.location; clipBoardContent+='\r\n'; window.clipboardData.setData("Text",clipBoardContent); alert("恭喜您!复制成功"); }
    分享到: 更多
    <script type="text/java script" id="bdshare_js" data="type=tools&uid=12732"> <script type="text/java script" id="bdshell_js"> <script type="text/java script"> var bds_config = {'snsKey':{'tsina':'2386826374','tqq':'5e544a8fdea646c5a5f3967871346eb8'}}; document.getElementById("bdshell_js").src = "http://bdimg.share.baidu.com/static/js/shell_v2.js cdnversion=" + Math.ceil(new Date()/3600000)