私のJava初心者の質問に申し訳ありません。以下の割り当てはJava、クローン()の問題?
double[][] d = { { 1, 2, 3 }, { 4, 5, 6 }, { 1, 0, 1} };
Matrix A = new Matrix(d);
Matrix B= new Matrix(3,3);
A.test(B);
B.print();
結果は驚くべきもので呼び出す
B = A
に行われる方法テストインサイド以下のクラス
public class Matrix {
public final double[][] items;
private final int rows_count, columns_count;
public Matrix(final int rows_count_, final int columns_count_) {
rows_count = rows_count_; columns_count = columns_count_;
items = new double[rows_count][columns_count];
}
public Matrix(final double[][] data) {
rows_count = data.length;
columns_count = data[0].length;
items = new double[rows_count][columns_count];
for (int i = 0; i < rows_count; i++)
for (int j = 0; j < columns_count; j++)
}
public Matrix copy() {
Matrix AC = new Matrix(rows_count, columns_count);
for (int i = 0; i < rows_count; i++)
for (int j = 0; j < columns_count; j++)
AC.items[i][j] = items[i][j];
return AC;
}
public Matrix clone() { return this.copy }
public void test (Matrix B) {
B = this.clone();
B.items[0][0] = 1;
}
にあります。にもかかわらず、
B = this.clone()
であり、得られるBマトリックスはゼロである。
0.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
Bが(テストを書き換え:-)値によって渡されたかのように行列Bが正しく
1.0 0.0 0.0
0.0 0.0 0.0
0.0 0.0 0.0
変更され
public void test (Matrix B) {
B.items[0][0] = 1;
}
ようにどこに問題がある)に見えますおそらく間違って書かれたコピー/クローンメソッド?どのように問題を解決し、割り当てを実行するB = A?ご協力いただきありがとうございます。
'B'内部の ' test() 'は' Matrix'の新しいインスタンスに設定されます。元の行列は変更されません。 – Phylogenesis
@ Phylogenesis:正しい割り当てを書くにはB = A? – justik
あなたの呼び出しコードでは、 'B = A.copy();'を使います。インスタンスメソッド内でそれを実行しようとしないでください。 – Phylogenesis