Java中对象拷贝方式有哪几种?

1.引用拷贝

 

        Person p = new Person();
        p.setAge(1);
        p.setName("jack");
        p.setDog(new Dog("tom..."));
        Person p1 = p;
        System.err.println("p=" +p +",p1="+p1);

 2.浅拷贝

 

package com.xx.tt.copy;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/***
 *
 *  @author xxxxx
 *  @date 2018-09-25 10:00
 */
public class Person  implements Cloneable{


    private String name;
    private int age;



    private Dog dog;


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {



        try {

            Object o = super.clone();
          Person p =  (Person) o;

         

            return p;
        }catch (CloneNotSupportedException e){
                e.printStackTrace();
        }
        return null;

    }


    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
    }
}

 

3.深拷贝

package com.xx.tt.copy;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;

/***
 *
 *  @author xxx
 *  @date 2018-09-25 10:00
 */
public class Person  implements Cloneable{


    private String name;
    private int age;



    private Dog dog;


    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public Dog getDog() {
        return dog;
    }

    public void setDog(Dog dog) {
        this.dog = dog;
    }

    @Override
    protected Object clone() throws CloneNotSupportedException {



        try {

            Object o = super.clone();
          Person p =  (Person) o;

            Object dog = this.dog.clone();
            p.dog = (Dog) dog;

            return p;
        }catch (CloneNotSupportedException e){
                e.printStackTrace();
        }
        return null;

    }


    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this, ToStringStyle.SIMPLE_STYLE);
    }
}

        实际上浅拷贝和深拷贝实现Cloneable接口并重写clone方法,区别是浅拷贝只实现自己本身的拷贝,深拷贝是拷贝自己和自己的非基础数据类型的成员也要依次拷贝

 

 4.串行化拷贝

     特点必须实现Serialable接口,使用ObjectInputStream和ObjectOutputStream两个类来实现复制拷贝功能(序列化和反序列化)。

 

你可能感兴趣的:(java面试题,面试)