创建的本地副本与克隆 : 克隆 « 类 « Java

En
Java
1. 图形用户界面
2. 三维图形动画
3. 高级图形
4. 蚂蚁编译
5. Apache类库
6. 统计图
7. 
8. 集合数据结构
9. 数据类型
10. 数据库JDBC
11. 设计模式
12. 开发相关类
13. EJB3
14. 电子邮件
15. 事件
16. 文件输入输出
17. 游戏
18. 泛型
19. GWT
20. Hibernate
21. 本地化
22. J2EE平台
23. 基于J2ME
24. JDK-6
25. JNDI的LDAP
26. JPA
27. JSP技术
28. JSTL
29. 语言基础知识
30. 网络协议
31. PDF格式RTF格式
32. 映射
33. 常规表达式
34. 脚本
35. 安全
36. Servlets
37. Spring
38. Swing组件
39. 图形用户界面
40. SWT-JFace-Eclipse
41. 线程
42. 应用程序
43. Velocity
44. Web服务SOA
45. 可扩展标记语言
Java 教程
Java »  » 克隆屏幕截图 
创建的本地副本与克隆
创建的本地副本与克隆
  

// : appendixa:LocalCopy.java
// Creating local copies with clone().
// From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002
// www.BruceEckel.com. See copyright notice in CopyRight.txt.


class MyObject implements Cloneable {
  private int n;

  public MyObject(int n) {
    this.n = n;
  }

  public Object clone() {
    Object o = null;
    try {
      o = super.clone();
    catch (CloneNotSupportedException e) {
      System.err.println("MyObject can't clone");
    }
    return o;
  }

  public int getValue() {
    return n;
  }

  public void setValue(int n) {
    this.n = n;
  }

  public void increment() {
    n++;
  }

  public String toString() {
    return Integer.toString(n);
  }
}

public class LocalCopy {

  public static MyObject g(MyObject v) {
    // Passing a reference, modifies outside object:
    v.increment();
    return v;
  }

  public static MyObject f(MyObject v) {
    v = (MyObjectv.clone()// Local copy
    v.increment();
    return v;
  }

  public static void main(String[] args) {
    MyObject a = new MyObject(11);
    MyObject b = g(a);
    // Reference equivalence, not object equivalence:
    System.out.println("a == b: " (a == b"\na = " + a + "\nb = " + b);
    MyObject c = new MyObject(47);
    MyObject d = f(c);
    System.out.println("c == d: " (c == d"\nc = " + c + "\nd = " + d);

  }
///:~


           
         
    
  
Related examples in the same category
1. 克隆
2. 类被宣布为cloneable 。
3. 数组自动cloneable
4. 克隆对象
5. 创建一个深度复制
6. 浅复制测试浅复制测试
7. 深复制测试深复制测试
8. 利用序列进行深拷贝克隆。
9. 克隆试验克隆试验
10. 可以插入Cloneability在任何层次上的继承
11. 克隆组成对象克隆组成对象
12. 序列和克隆序列和克隆
13. Go through a few gyrations to add cloning to your own classGo through a few gyrations to add cloning to your own class
14. Checking to see if a reference can be clonedChecking to see if a reference can be cloned
15. The clone operation works for only a few items in the standard Java libraryThe clone operation works for only a few items in the standard Java library
16. 示范克隆
17. 简单的演示避免副作用使用Object.clone简单的演示避免副作用使用Object.clone
18. 克隆对象与Clone方法从父
19. 操控性能在克隆操作
20. 克隆演示
www.java2java.com | Contact Us
Copyright 2010 - 2030 Java Source and Support. All rights reserved.
All other trademarks are property of their respective owners.