0

I'm making my own Java matrix program for a linear algebra class and can't seem to stop passing my arrays by reference. I want each method to return a matrix (thus performing calculations based on the original) without altering the original matrix values. Here are some bits from my program below:

public class Matrix{
    private Double[][] data;
    private String name;

    public Matrix(Double[][] newdata){
        this.data = newdata.clone();
        this.name = "default";
    }

    public Matrix scalarMultiply(Double scale){
        Matrix output = new Matrix(this.data.clone());
        output.name = scale + "(" + output.name + ")";
        for(int i = 0; i < output.data.length; i++){
            for(int j = 0; j < output.data[i].length; j++){
                output.data[i][j] *= scale;
            }
        }

        return output;
    }
}
public class Main {
    public static void main(String[] args) throws Exception{
        new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();

        Matrix testMatrix = new Matrix(new Double[][]{{1.0, 2.0, 3.0}, {4.0, 5.0, 6.0}, {7.0, 8.0, 9.0}, {100.0, 101.0, 102.0}});
        testMatrix.printSpacedAuto();
        breakLine();

        Matrix testMatrixRestult = testMatrix.scalarMultiply(2.0);
        testMatrixRestult.printSpacedAuto();
        breakLine();

        testMatrix.printSpacedAuto();
        testMatrixRestult.printSpacedAuto();
        breakLine();
    }

    public static void breakLine(){
        System.out.println();
    }
}

I tried using a.clone() in a few different spots but my results seem the same; can anyone see what I am misunderstanding?

Aidan K
  • 1
  • 3
  • You make a "deep copy" of a 2D array, and then use it. – Hovercraft Full Of Eels Jul 16 '23 at 20:48
  • @HovercraftFullOfEels Does using `a.clone()` not do that? I thought the whole point of it was to make a new version without reference to the old? Or does it only work correctly on 1D arrays? – Aidan K Jul 16 '23 at 20:51
  • Your use of clone creates a "shallow" copy, not a deep one. Please Google the difference, since the behavioral differences are significant, as you are finding out -- essentially, you want to create copies of nested objects, which clone by itself, is not doing. Also, in general it is best to avoid use of clone. – Hovercraft Full Of Eels Jul 16 '23 at 20:53
  • Please have a look at what Stephen C has to say about this topic [here](https://stackoverflow.com/a/6183597/). – Hovercraft Full Of Eels Jul 16 '23 at 20:55
  • Semantic note: Java is "pass-by-value" always. Please see: [Is Java "pass-by-reference" or "pass-by-value"?](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value) – Hovercraft Full Of Eels Jul 16 '23 at 20:57

0 Answers0