I have an object I created that has a number of properties, including a jagged array property, called matrix.
In my script, I want to clone a copy of the object and place it into an arraylist of my object. however i am not able to get a cloned copy of the matrix property to set correctly, as it keeps passing the last known reference into my list. Code below
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));
}
...and for the object class I have been doing a bunch of things, but generally this
public class MatrixObject
{
public Date startDate;
public int[][] matrix;
public MatrixObject (MatrixObject copy) {
this.startDate = copy.startDate;
this.matrix = copy.Matrix;
}
I also created this method in the class, but I dont think its working
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;
}
If there is a better way to add a clone of the object into the list, that will work as well. I am easy, just trying to figure this thing out.
Dates in one place is strange. What exactly is it that you are trying to do?public MatrixObject(int[][] inputMatrix)which makes a copy ofinputMatrixin the same manner asSetMatrix.SetMatrixdoes not "set" anything, nor does it interact with instance variables: it should be calledcopyMatrixand made static.