wesleyNeill wesleyNeill - 29 days ago 12
Java Question

Java: How to access a 2D array contained in an object list

I wanted to make an array of 2D arrays, but was pointed towards an ArrayList by a member here, and following his suggestion I wrote the following code:

public class matrixArray {
double[][] array;
public matrixArray(double[][] initialArray){
array = initialArray;
}
}


I then implemented it by the following:

public static ArrayList LUDecompose(double[][] A){

ArrayList<matrixArray> LU = new ArrayList<>();
double[][] L = new double[A.length][A.length];
double[][] U = new double[A.length][A.length];

for(int j=0; j<(A.length-1);j++){
for(int i=(j+1); i<A.length; i++){

double lower = A[i][j]/A[j][j];
L[i][j] = lower;

double[] replacement = row_scalar_mult(lower,A[j]);
replacement = vector_add(replacement, A[i]);

row_replace(i, A, replacement);
}
}

LU.add(new matrixArray(L));
LU.add(new matrixArray(A));

return LU;
}


So far so good. Now, I want to access the 2D arrays in my fancy new ArrayList. When I try the following code in my main method, I get the error "Incompatible types: Object cannot be converted to double[][]":

double[][] L = LUDecompose(A).get(0);
double[][] U = LUDecompose(A).get(0);


OR

ArrayList LU = LUDecompose(A);
double[][] L = LUDecompose(A).get(0);
double[][] U = LUDecompose(A).get(0);


So my question becomes: How do I access the "Object" to get out my treasured 2D Arrays?

Answer

You need to specify the proper return type in the method signature:

public static ArrayList<matrixArray> LUDecompose(double[][] A){

note the use of ArrayList<matrixArray> rather than just ArrayList

then use

ArrayList LU = LUDecompose(A);
double[][] L = LUDecompose(A).get(0).array;
double[][] U = LUDecompose(A).get(0).array;
Comments