ret person 图片 引用 exception png 指向 pri ima
- 克隆顾名思义就是,参照一个东西再做一个出来
- 浅克隆:直接复写Object的clone()方法,默认情况下8种基本数据类型和String都会进行深克隆,另外的其他引用类型为浅克隆(浅克隆:引用指向的是同一个对象)
- 深克隆:浅克隆中那另外的其他引用类型都让其变为深克隆
引用类型图解
- public class Main {
- public static void main(String[] args) throws Exception {
- A a = new A();
- A b = (A) a.clone();
- b.str = "....";
- b.i = 1000;
- System.out.println(a == b); //false 表示地址并不一样,不是同一个引用
- System.out.println(a.p == b.p); //true 表示引用类型只想的是同一个引用
- System.out.println(a.str == b.str); //false 表示地址并不一样,不是同一个引用
- System.out.println(a.i == b.i); //false 表示地址并不一样,不是同一个引用
- }
- }
- //克隆对象需要实现Cloneable接口
- class A implements Cloneable {
- Person p = new Person("谭迪");
- String str = "hehe";
- int i = 100;
- //浅克隆:该方法来自于Object
- @Override protected Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
- class Person {
- String name;
- public Person(String name) {
- this.name = name;
- }
- }
Java 浅克隆和深克隆
- public class Main {
- public static void main(String[] args) throws Exception {
- A a = new A();
- A b = (A) a.clone();
- b.str = "....";
- b.i = 1000;
- System.out.println(a == b); //false
- System.out.println(a.p == b.p); //flase
- System.out.println(a.str == b.str); //flase
- System.out.println(a.i == b.i); //flase
- }
- }
- //克隆对象需要实现Cloneable接口
- class A implements Cloneable {
- Person p = new Person("小明");
- String str = "hehe";
- int i = 100;
- //深克隆:该方法来自于Object
- @Override protected A clone() throws CloneNotSupportedException {
- A a = (A) super.clone();
- a.p = (Person) p.clone();
- return a;
- }
- }
- class Person implements Cloneable {
- String name;
- public Person(String name) {
- this.name = name;
- }@Override protected Object clone() throws CloneNotSupportedException {
- return super.clone();
- }
- }
来源: http://www.bubuko.com/infodetail-2447749.html