Java clone()

1.java里的clone分为:
A:浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。

b:深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。

Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点

1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。

2.在派生类的clone()方法中,调用super.clone()。

3.在派生类中实现Cloneable接口。

Object类里的clone方法是浅复制(浅克隆)

浅复制(浅克隆)的例子如下:

//浅复制(浅克隆): 浅复制仅仅复制所考虑的对象,而不复制它所引用的对象。
//深复制(深克隆):深复制把要复制的对象所引用的对象都复制了一遍。
//
//Java中对象的克隆,为了获取对象的一份拷贝,我们可以利用Object类的clone()方法。必须要遵循下面三点
//1.在派生类中覆盖基类的clone()方法,并声明为public【Object类中的clone()方法为protected的】。
//2.在派生类的clone()方法中,调用super.clone()。
//3.在派生类中实现Cloneable接口。
  public class Clone {
    public static void main(String[] args) throws Exception {
        // teacher对象将被clone出来的Student对象共享.
        Teacher teacher = new Teacher();
        teacher.setAge(40);
        teacher.setName("Teacher zhang");

        Student student1 = new Student();
        student1.setAge(20);
        student1.setName("zhangsan");
        student1.setTeacher(teacher);

        // 复制出来一个对象student2
        Student student2 = (Student) student1.clone();
        System.out.println(student2.getAge());
        System.out.println(student2.getName());

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
        System.out.println(student1.getTeacher().getAge());
        System.out.println(student1.getTeacher().getName());

        // 修改student2的引用对象
        student2.getTeacher().setAge(50);
        student2.getTeacher().setName("Teacher Li");

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
        System.out.println(student1.getTeacher().getAge());
        System.out.println(student1.getTeacher().getName());
    }
}

class Teacher {
    public int age;
    public String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

class Student implements Cloneable {

    public int age;
    public String name;
    public Teacher teacher;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

}
  1. 输出结果为:
  2. 20
  3. zhangsan
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. 40
  6. Teacher zhang
  7. ~~~~~~~~~~~~~~~~~~~~~~
  8. 50
  9. Teacher Li
 

2.深复制(深Clone)例子:

 1 public class DeepClone {
 2
 3
 4         public static void main(String[] args) throws Exception {
 5             // teacher对象将不被clone出来的Student对象共享.
 6             Teacher teacher = new Teacher();
 7             teacher.setAge(40);
 8             teacher.setName("Teacher zhang");
 9
10             Student student1 = new Student();
11             student1.setAge(20);
12             student1.setName("zhangsan");
13             student1.setTeacher(teacher);
14
15             // 复制出来一个对象student2
16             Student student2 = (Student) student1.clone();
17             System.out.println(student2.getAge());
18             System.out.println(student2.getName());
19
20             System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
21             System.out.println(student1.getTeacher().getAge());
22             System.out.println(student1.getTeacher().getName());
23
24             // 修改student2的引用对象
25             student2.getTeacher().setAge(50);
26             student2.getTeacher().setName("Teacher Li");
27
28             System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
29             System.out.println(student1.getTeacher().getAge());
30             System.out.println(student1.getTeacher().getName());
31         }
32     }
33
34     class Teacher implements Cloneable {
35         public int age;
36         public String name;
37
38         public int getAge() {
39             return age;
40         }
41
42         public void setAge(int age) {
43             this.age = age;
44         }
45
46         public String getName() {
47             return name;
48         }
49
50         public void setName(String name) {
51             this.name = name;
52         }
53
54         @Override
55         public Object clone() throws CloneNotSupportedException {
56             return super.clone();
57         }
58
59     }
60
61     class Student implements Cloneable {
62
63         public int age;
64         public String name;
65         public Teacher teacher;
66
67         public int getAge() {
68             return age;
69         }
70
71         public void setAge(int age) {
72             this.age = age;
73         }
74
75         public String getName() {
76             return name;
77         }
78
79         public void setName(String name) {
80             this.name = name;
81         }
82
83         public Teacher getTeacher() {
84             return teacher;
85         }
86
87         public void setTeacher(Teacher teacher) {
88             this.teacher = teacher;
89         }
90
91         @Override
92         public Object clone() throws CloneNotSupportedException {
93             Student student = (Student) super.clone();
94             // 将引用的对象teacher也clone下
95             student.setTeacher((Teacher)(student.getTeacher().clone()));
96             return student;
97         }
98
99     }
  1. 输出结果为:
  2. 20
  3. zhangsan
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. 40
  6. Teacher zhang
  7. ~~~~~~~~~~~~~~~~~~~~~~
  8. 40
  9. Teacher zhang

3.利用序列化来做深复制,把对象写到流里的过程是序列化(Serilization)过程,而把对象从流中读出来的过程则叫做反序列化(Deserialization)过程。应当指出的是,写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。,利用这个特性,可以做深拷贝

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//利用序列化来做深复制
//深clone
public class DeepCloneTest {  

    public static void main(String[] args) throws Exception{
        //teacher对象将不被clone出来的Student对象共享.
        Teacher teacher = new Teacher();
        teacher.setAge(40);
        teacher.setName("Teacher zhang");  

        Student student1 = new Student();
        student1.setAge(20);
        student1.setName("zhangsan");
        student1.setTeacher(teacher);  

        //复制出来一个对象student2
        Student student2 = (Student)student1.deepCopy();
        System.out.println(student2.getAge());
        System.out.println(student2.getName());  

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
        System.out.println(student1.getTeacher().getAge());
        System.out.println(student1.getTeacher().getName());  

        //修改student2的引用对象
        student2.getTeacher().setAge(50);
        student2.getTeacher().setName("Teacher Li");  

        System.out.println("~~~~~~~~~~~~~~~~~~~~~~");
        System.out.println(student1.getTeacher().getAge());
        System.out.println(student1.getTeacher().getName());
    }
}  

class Teacher implements Serializable{  

    private static final long serialVersionUID = -8834559347461591191L;  

    public int age;
    public String name;  

    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  

}  

class Student implements Serializable{  

    //serialVersionUID 如果你的对象序列化后存到硬盘上面后,可是后来你却更改了类的field(增加或减少或改名),当你反序列化时,就会出现Exception的,这样就会造成不兼容性的问题。
    //但当serialVersionUID相同时,它就会将不一样的field以type的缺省值赋值(如int型的是0,String型的是null等),这个可以避开不兼容性的问题。所以最好给serialVersionUID赋值
    private static final long serialVersionUID = 7991552226614088458L;  

    public int age ;
    public String name;
    public Teacher teacher;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Teacher getTeacher() {
        return teacher;
    }
    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }  

    public Object deepCopy() throws Exception{
        //将该对象序列化成流,因为写在流里的是对象的一个拷贝,而原对象仍然存在于JVM里面。所以利用这个特性可以实现对象的深拷贝
        ByteArrayOutputStream bos = new ByteArrayOutputStream();  

        ObjectOutputStream oos = new ObjectOutputStream(bos);  

        oos.writeObject(this);  

        //将流序列化成对象
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());  

        ObjectInputStream ois = new ObjectInputStream(bis);  

        return ois.readObject();
    }  
  1. 输出结果为:
  2. 20
  3. zhangsan
  4. ~~~~~~~~~~~~~~~~~~~~~~
  5. 40
  6. Teacher zhang
  7. ~~~~~~~~~~~~~~~~~~~~~~
  8. 40
  9. Teacher zhang
 

Java clone()

时间: 2024-10-08 14:17:39

Java clone()的相关文章

Java clone()深拷贝、浅拷贝

Cloneable接口是一个空接口,仅用于标记对象,Cloneable接口里面是没有clone()方法,的clone()方法是Object类里面的方法!默认实现是一个Native方法 protected native Object clone() throws CloneNotSupportedException; 如果对象implement Cloneable接口的话,需要覆盖clone方法(因为Object类的clone方法是protected,需要覆盖为public) public Obj

Java clone() 浅克隆与深度克隆

内容转自:http://www.blogjava.net/orangelizq/archive/2007/10/17/153573.html 现在Clone已经不是一个新鲜词语了,伴随着“多莉”的产生这个词语确实很“火”过一阵子,在java中也有这么一个概念,它可以让我们很方便的“制造”出一个对象的副本来,下面来具体看看java中的Clone机制是如何工作的?     1. Clone&Copy     假设现在有一个Employee对象,Employee tobby =new Employee

Java clone()方法使用说明

Java语言的一个优点就是取消了指针的概念,但也导致了许多程序员在编程中常常忽略了对象与引用的区别,并且由于Java不能通过简单的赋值来解决对象复制的问题,在开发过程中,也常常要要应用clone()方法来复制对象. 比如函数参数类型是自定义的类时,此时便是引用传递而不是值传递.下面是举例: Java代码   public class A { public String name; } Java代码   public class testClone { public void changeA(A 

关于Java clone(浅克隆) 的代码

1 import java.util.Date; 2 3 public class HelloWorld{ 4 public static void main(String[] args) throws CloneNotSupportedException{ 5 Student stu1 = new Student(); 6 Student stu2 = (Student)stu1.clone(stu1); 7 8 System.out.println(stu1); 9 System.out.p

Java clone方法(下)

1.最终调用的是一个JNI方法,即java本地方法,加快速度 2.使用clone方法,分为浅复制.深复制,这里直接使用网上抄来的案例来说明吧: 说明: 1)为什么我们在派生类中覆盖Object的clone()方法时,一定要调用super.clone()呢?在运行时刻,Object中的clone()识别你要复制的是哪一个对象,然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中. 2)继承自java.lang.Object.clone()方法是浅层复制.一下代码可以

Java clone() 浅克隆与深度克隆(转)

以下文字转自:桔子园 http://www.blogjava.net/orangelizq/archive/2007/10/17/153573.html 现在Clone已经不是一个新鲜词语了,伴随着“多莉”的产生这个词语确实很“火”过一阵子,在java中也有这么一个概念,它可以让我们很方便的“制造”出一个对象的副本来,下面来具体看看java中的Clone机制是如何工作的?     1. Clone&Copy     假设现在有一个Employee对象,Employee tobby =new Em

[Leetcode][JAVA] Clone Graph, Copy List with Random Pointer

Clone Graph: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected graph serialization: Nodes are labeled uniquely. We use # as a separator for each node, and , as a separator for node label a

[LeetCode][Java] Clone Graph

题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. OJ's undirected graph serialization: Nodes are labeled uniquely. We use # as a separator for each node, and , as a separator for node label and each n

Is C# a clone of a Microsoft replacement for Java?

Is C# a clone of a Microsoft replacement for Java?Let's look at what Anders Hejlsberg Said. Hejlsberg: First of all, C# is not a Java clone. In the design of C#, we looked at a lot of languages. We looked at C++, we looked at Java, at Modula 2, C, an