我创建了一个 Matrix 对象(例如数学矩阵,一个 4x4 的数字 block )并且它工作正常,可以很好地设置行、列、变量,但是,我不能拥有多个相同的对象,我让它创建一个由十几个 Matrix 对象组成的 ArrayList,每个对象都有三个变量,但是当我调用 changeVar(Matrix x,int variable) 并刷新矩阵的打印输出时,它将所有数字更改为我更改变量的值到。所以看起来它只是一遍又一遍地创建相同的实例,如果你更改一个实例,它就会更改所有实例,我是否遗漏了任何明显的东西?
public class Matrices {
private static int row, col, value, newRow, newCol;
public Matrices(int row, int col, int value) {
this.value = value;
this.row = row;
this.col = col;
}
public static void setRow(int row) {
Matrices.row = row;
}
public static void setValue(int value) {
Matrices.value = value;
}
public static void setCol(int col) {
Matrices.col = col;
}
public static int getCol(Matrices x) {
return col;
}
public static int getRow(Matrices x) {
return row;
}
public static int getValue(Matrices x) {
return value;
}
public static Matrices changeValue(Matrices x, int value) {
newRow = getRow(x);
newCol = getCol(x);
return new Matrices(newRow, newCol, value);
}
}
最佳答案
问题在于您使用了“static”关键字。
简短的答案是:删除所有静态关键字。
更长的答案是静态字段/方法不与类的任何特定实例关联,因此您的代码所做的是设置一个名为“row”的字段,一个名为“col”等的字段,并将它们用于所有实例类(class)的。您真正想要的是每个实例一个字段:使字段成为非静态将实现这一点。
一般来说,避免使用静态,除非你真的真的这么想,即如果你想要一个单例类,或者你有一个不应实例化的实用程序类。
关于java - 创建对象[同一实例的多个],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3973427/