0

5 つの Employee オブジェクトを含む EmployeeList があるとします。

その EmployeeList のクローンを実行して新しい EmployeeList を作成したいのですが、どうすればよいのでしょうか?

したがって、以下は私のクラスの従業員です。

public class Employee {
private String name;
private String ssn;
private double salary;

private String name() {
    return name;
}

private void name(String name) {
    this.name = name;
}

private String ssn() {
    return ssn;
}

private void ssn(String ssn) {
    this.ssn = ssn;
}

private double salary() {
    return salary;
}

private void salary(double salary) {
    this.salary = salary;
}

void initialize(String initName, String initSsn, double initSalary) {
    this.name(initName);
    this.ssn(initSsn);
    this.salary(initSalary);
}

public Employee(String name, String ssn, double salary) {
    this.initialize(name, ssn, salary);
}

public Employee clone() {
    return new Employee(this.name, this.ssn, this.salary);
}
}

そして、以下は私のクラスEmployeeListです:

public class EmployeeList implements Cloneable {
private Employee[] list;
private int MAX = 5;

public EmployeeList() {
    list = new Employee[MAX];
    for (int i = 0; i < MAX; i++)
        list[i] = null;
}

public void add(Employee employee) {
    list[count] = employee;
}

public Object clone() {
    try {
        return super.clone();
    } catch (CloneNotSupportedException c) {
        System.out.println(c);
        return null;
    }
}   
}

見やすいようにコードを短くしています。

私の問題は次のとおりです。

コピーを実行したとき、元の Employee オブジェクトを指すポインターを使用して EmployeeList をコピーしたと思います。元のオブジェクトを変更すると、新しいリストのオブジェクトも変更されるため

とにかく私はそれを修正することができますか?

どうもありがとうございました。

4

2 に答える 2

1

うん、それはまさにあなたが思っていたことをしました - それはあなたの配列をその値を含めて複製しました. この場合の配列値は従業員のインスタンスへのポインターであるため、同じ従業員を指す 2 番目の配列を取得します。それは浅いコピーと呼ばれます。完全なコピーが必要な場合は、次のようなものが必要です

public Object clone() {
    try {
        EmployeeList copy = (EmployeeList) super.clone();
        if (list!=null) {
            copy.list = new Employee[list.length];
            for (int i=0; i<list.length; i++) {
                copy.list[i] = (Employee)list[i].clone();
            }
        } else {
            copy.list = null;
        }
        return copy;
    } catch (CloneNotSupportedException c) {
        System.out.println(c);
        return null;
    }
}

また、Employee を複製可能にする必要があります。一般に、オブジェクトのグラフを扱う場合、各オブジェクトの clone() メソッドは、プリミティブ ( などdouble) または不変クラス (一度構築すると変更できないクラス -Stringあなたの場合のように) にヒットするまで、そのデータ メンバーを再帰的に複製する必要があります。

于 2013-02-10T06:12:25.843 に答える
0

では、シャロー コピーを行うEmployeeList.cone()を呼び出す代わりに、以下の疑似コードのようにsuper.clone()、代わりにリスト要素を反復処理し、clone()各オブジェクトで呼び出す必要があります。Employee

EmployeeList.clone() {
   EmployeeList newList = (EmployeeList) super.clone();
   int i=0;
   for (Employee emp: this.list){
      newList[i++] = (Employee) emp.clone();
   }
   return newList;
}

使用しない他のオプションは、CloneableインターフェイスSerializableを使用し、Apache commons SerializationUtils のようなユーティリティを使用してオブジェクトをディープ クローンすることですhttp://commons.apache.org/lang/api-2.3/org/apache/commons/lang/SerializationUtils.html# clone%28java.io.Serializable%29

于 2013-02-10T06:19:29.280 に答える