Java简单深层复制

时间:2015-03-18 12:04:45

标签: java deep-copy

我已经在互联网上搜索了一个更基本的对象深度复制解决方案,它不需要序列化或其他外部Java工具。我的问题是你如何深度复制具有继承属性的对象,另外还有从其他对象聚合的对象? (不确定我是否说得正确..)

这与以下问题不同:“浅拷贝和深拷贝之间有什么区别”,因为这种类型的深拷贝有特定参数涉及继承和聚合(依赖其他对象作为其他对象的实例变量) )。

1 个答案:

答案 0 :(得分:0)

我找到了一个适用于继承和聚合的解决方案 - 这是一个简单的对象结构:

//This is our SuperClass
public class Human {

    private String hairColor; //Instance variable

    public Human (String color) { // Constructor
        hairColor = color; 
    }

    public String getHairColor () { //Accessor method
        return hairColor;
    }
}

//This is our beard object that our 'Man' class will use
public class Beard {

    private String beardColor; // Instance variable

    public Beard (String color) { // Constructor
        beardColor = color;
    }

    public String getBeardColor () { // Accessor method
        return beardColor;
    }
}

// This is our Man class that inherits the Human class attributes
// This is where our deep copy occurs so pay attention here!
public class Man extends Human {

    // Our only instance variable here is an Object of type Beard
    private Beard beard;

    // Main constructor with arg
    public Man (Beard aBeard, String hairColor) {
        super(hairColor);
        beard = aBeard;
    }

    // Here is the COPY CONSTRUCTOR - This is what you use to deep copy
    public Man (Man man) {
        this(new Beard(man.getBeard().getBeardColor()), man.getHairColor());
    }

    // We need this to retrieve the object Beard from this Man object
    public Beard getBeard () {
        return beard;
    }
}

对不起,这个例子并不是非常unisexy ...起初对我来说很有趣。

Beard对象只是为了展示我在使用继承和深层复制时遇到的一个更难的例子。这样,当您使用汇总时,您就会知道该怎么做。如果您不需要访问任何对象而只需要原语,那么它就可以使用类实例变量。

public class Man extends Human {

    private String moustache;
    private double bicepDiameter;

    public Man (String aMoustache, double bicepSize) {
        this.moustache = aMoustache;
        this.bicepDiameter = bicepSize;
    }

    // This is the simple (no-object) deep copy block
    public Man (Man man) {
        this(man.moustache, man.bicepDiameter);
    }
}  

我真的希望这会有所帮助!快乐的编码:)

相关问题