currently I have a class called MatrixValue
that I want to make into an immutable object so that all my methods that interact with an instance of MatrixValue
can't change its inner matrix. However, the problem is one of the member variables is a mutable object called RealMatrix
that stores all the actual data of the matrix. I've already put in defensive copying into the constructor and gotten rid of any mutator methods. Here is what my class looks like so far:
public final class MatrixValue extends ExpressionValue{
/**
*
*/
private static final long serialVersionUID = -4231050452116360135L;
private final RealMatrix matrix;
public MatrixValue(RealMatrix matrix){
this.matrix = new Array2DRowRealMatrix(matrix.getData());
}
public MatrixValue(double[][] values){
matrix = new Array2DRowRealMatrix(values);
}
public RealMatrix getMatrix() {
return matrix;
}
@Override
public String toString(){
return matrix.getRowDimension() + "," + matrix.getColumnDimension();
}
}
The problem right now is that if someone calls matrixValue.getMatrix().setEntry(row, col, value);
they are effectively able to change the value of the final RealMatrix
member variable. However, I still want to be able to return information regarding the RealMatrix
. What's the best approach to fixing this hole in the class's immutability?
EDIT: Also do keep in mind that some matrices can become memory intensive so if possible I would prefer a solution that minimizes duplicating unnecessary information if possible.