【发布时间】:2015-06-27 22:20:36
【问题描述】:
我创建了一个对象,该对象具有许多属性,包括一个锯齿状数组属性,称为矩阵。
在我的脚本中,我想克隆对象的副本并将其放入对象的数组列表中。但是我无法正确设置矩阵属性的克隆副本,因为它不断将最后一个已知引用传递到我的列表中。代码如下
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;
}
如果有更好的方法将对象的克隆添加到列表中,那也可以。我很容易,只是想弄清楚这件事。
【问题讨论】:
-
你有其他语言的背景,也许是 JavaScript?整个事情看起来好像您正在尝试使用 Java 关键字进行编程,但使用其他语言进行思考。复制和克隆某些东西通常是一个坏主意,您应该尽量保持一切不可变。在一个地方看到文本文件、矩阵和
Dates 很奇怪。你到底想做什么? -
部分问题似乎是您正在努力使复制构造函数“适合”您正在尝试做的事情,但您并不需要它。您应该改为使用
public MatrixObject(int[][] inputMatrix),它以与SetMatrix相同的方式复制inputMatrix。SetMatrix不“设置”任何东西,也不与实例变量交互:它应该被称为copyMatrix并设为静态。
标签: java object arraylist clone