如何在Java中实现包含对象数组的对象的深层副本?

阿克沙伊·达姆勒

我需要制作一个称为GarageImplement的类,Cloneable并重写该Object.clone()方法以制作一个类型为object的深层副本,Garage其中包含type的对象数组Vehicle

我已经阅读了几个Cloneable被打断的SO答案,不使用它是很明智的,但是我的实验室作业要求我实现Cloneable并编写一个正确的clone()方法。我已经寻找了很长时间,但仍然无法做到这一点。任何帮助将非常感激。

这是我Garage上课的代码

public class Garage extends Vehicle implements Cloneable {
    // array to store up to 15 Vehicle objects
    Vehicle array[] = new Vehicle[15];

    // overriding the clone method to perform a deeper copy
    @Override
    protected Object clone() throws CloneNotSupportedException {
        //TODO
    }
}

这是我Vehicle上课的代码

public class Vehicle {
    int numWheels;
    int ID;
    String name;
}
他们是

首先是Garage extends Vehicle没有道理的。我认为这是一个错误。一个Garage不是一个Vehicle

Garage你可以实现clone为:

@Override
protected Object clone() {
    Garage other = new Garage ();
    for (Vehicle v : this.array) {
        other.addVehicle((Vehicle)v.clone());
    }
    return other;
}

然后,您必须clone()Vehicle类层次结构中实现。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章