提问人:Aidan K 提问时间:7/17/2023 最后编辑:Aidan K 更新时间:7/17/2023 访问量:24
如何避免在方法(Java)内部通过引用传递?[复制]
How to avoid passing by reference inside of method (Java)? [duplicate]
问:
我正在为线性代数类制作自己的 Java 矩阵程序,并且似乎无法停止通过引用传递我的数组。我希望每个方法在不更改原始矩阵值的情况下返回一个矩阵(从而基于原始矩阵执行计算)。以下是我的程序中的一些内容:
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();
}
}
我尝试在几个不同的地方使用,但我的结果似乎是一样的;谁能看出我在误解什么?a.clone()
答: 暂无答案
评论