簡體   English   中英

將對象克隆到數組列表中,java

[英]Clone Object into array list, java

我創建了一個對象,該對象具有許多屬性,包括鋸齒狀數組屬性,稱為矩陣。

在我的腳本中,我想克隆對象的副本並將其放入對象的arraylist中。 但是我無法正確設置matrix屬性的克隆副本,因為它會將最新的已知引用不斷傳遞到我的列表中。 下面的代碼

MatrixObject newMatrixObject = new MatrixObject();
List<MatrixObject> listMatrix = new ArrayList<MatrixObject>();

try {  //some code here looking int text file

    int[][] myArray = some value;
    newMatrixObject.matrix = myArray; //this works but keeps changing to the last value of myArray
    //I tried this as well
    newMatrixObject.matrix = newMatrixObject.SetMatrix(myArray); // didnt work either and I tried setting it without returning an array, same story
    listMatrix.add(new MatrixObject(newMatrixObject));
}

...對於對象類,我一直在做很多事情,但是通常

public class MatrixObject 
{
    public Date startDate;
    public int[][] matrix;

    public MatrixObject (MatrixObject copy) {

        this.startDate = copy.startDate;
        this.matrix = copy.Matrix;
}

我也在課堂上創建了這個方法,但是我認為它不起作用

public  int[][] SetMatrix(int[][] inputMatrix){
    //if (inputMatrix == null){
    //return null;
    //}

    int [][] result = new int [inputMatrix.length][];
    for ( int i= 0; i< inputMatrix.length; i++)
    {
       result[i] = Arrays.copyOf(inputMatrix[i], inputMatrix[i].length);
    }

    System.out.println(Arrays.deepToString(result));
    return result;
}

如果有更好的方法將對象的副本添加到列表中,那么該方法也將起作用。 我很容易,只是想弄清楚這件事。

很難確切說明您在做什么,但我認為問題在於構造函數。

public MatrixObject (MatrixObject copy) {

    this.startDate = copy.startDate;
    this.matrix = copy.matrix;
}

這將使MatrixObject共享copy的內部信息,因此您對新MatrixObject或舊MatrixObject任何更改實際上都會更改另一個。 相反,您應該復制所有字段,如下所示:

public MatrixObject (MatrixObject copy) {

    this.startDate = new Date(copy.startDate.getTime());
    this.matrix = new int[copy.matrix.length][];
    for (int i = 0; i < copy.matrix.length; i++)
        this.matrix[i] = Arrays.copyOf(copy.matrix[i], copy.matrix[i].length);
}

使用后跟類名的new復制對象通常會導致代碼不可擴展。 使用clone原型模式的應用)是一種更好的方法。 但是,使用Java中提供的clone也可能會產生問題。

最好從clone方法中調用非公共副本構造函數。 這使我們能夠將創建對象的任務委托給類本身的實例,從而提供可擴展性,並且還可以使用非公共副本構造函數安全地創建對象。

下面是對MatrixObject類的重做。 它顯示了如何依靠構建過程來安全地實現clone 這在班級包含final字段的情況下尤其有用。

MatrixObject類

import java.util.*;

public class MatrixObject implements Cloneable {
    private Date startDate;
    private int[][] matrix;

    public MatrixObject(Date newDate, int[][] newMatrix) {
        this.startDate = newDate;
        this.matrix = newMatrix;
    }

    protected MatrixObject(MatrixObject another) {
        Date refDate = null;
        int[][] refMatrix = null;

        refDate = (Date) another.startDate.clone();
        refMatrix = another.matrix.clone();

        this.matrix = refMatrix;
        this.startDate = refDate;
    }

    public void setMatrix(int[][] newMatrix) {
        this.matrix = newMatrix;
    }

    public void setDate(Date newDate) {
        this.startDate = newDate;
    }

    public String toString() {
        String s = "";

        for (int[] tmp : this.matrix) {
            s += Arrays.toString(tmp) + "\n";
        }

        return String.format("%s%n%s", this.startDate.toString(), s);
    }

    @Override
    public Object clone() {
        return new MatrixObject(this);
    }

    // MAIN GOES HERE (or anywhere in this class that is outside of a method)
    // static void main(String[] args) { ... }

}

主要方法

public static void main(String[] args) {
    String output = "";
    Calendar dates = Calendar.getInstance();
    Date dateOne = dates.getTime();
    // offset day of the month by one day
    dates.set(Calendar.DAY_OF_MONTH, dates.get(Calendar.DAY_OF_MONTH) + 1);
    Date dateTwo = dates.getTime();

    int[][] myArrayOne = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 }, };
    int[][] myArrayTwo = { { 0, 0, 1 }, { 0, 1, 0 }, { 1, 0, 0 }, };

    // create two MatrixObjects, an original and a copy
    MatrixObject oneMO = new MatrixObject(dateOne, myArrayOne);
    MatrixObject copyMO = (MatrixObject) oneMO.clone();

    // show the contents of the original MatrixObject and its copy
    output += String.format("First MatrixObject:%n%s%n", oneMO.toString());
    output += String
    .format("Copied MatrixObject:%n%s%n", copyMO.toString());

    // alter the original MatrixObject
    oneMO.setMatrix(myArrayTwo);
    oneMO.setDate(dateTwo);

    // show that alterations to the original MatrixObject did not
    // effect the copy
    output += String.format("Changed First MatrixObject:%n%s%n",
    oneMO.toString());
    output += String.format("Unchanged Copied MatrixObject:%n%s%n",
    copyMO.toString());

    System.out.println(output);
}

輸出量

First MatrixObject:
Mon Apr 20 21:29:14 EDT 2015
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]

Copied MatrixObject:
Mon Apr 20 21:29:14 EDT 2015
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]

Changed First MatrixObject:
Tue Apr 21 21:29:14 EDT 2015
[0, 0, 1]
[0, 1, 0]
[1, 0, 0]

Unchanged Copied MatrixObject:
Mon Apr 20 21:29:14 EDT 2015
[1, 0, 0]
[0, 1, 0]
[0, 0, 1]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM