即使我已经将Face类声明为final类,它似乎也不是一成不变的,该如何更正呢? [英] My Face class does not seem to be immutable even though I already declared it as final, how do I correct it?
问题描述
我试图使Face类不可变,以使Face对象一旦初始化就不会更改.这是我到目前为止的内容:
I am trying to make my Face class immutable such that my Face object will not change once it has been initialized. This is what I have so far:
public class Face{
protected final int[][] grid;
protected Face half;
public Face(int[][] grid){
this.grid = grid;
}
public Face rotateRight(){
int rows = 3;
int cols = 3;
int[][] transposedArray = new int[3][3];
for (int i = 0; i<rows; i++){
for (int j = 0; j<cols; j++){
transposedArray[i][j]=grid[rows-j-1][i];
}
}
return new Face(transposedArray);
}
public Face rotateLeft(){
int rows = 3;
int cols = 3;
int[][] transposedArray = new int[3][3];
for (int i = 0; i < 3; i++){
for (int j = 0; j < 3; j++){
transposedArray[2-j][i] = grid[i][j];
}
}
return new Face(transposedArray);
}
public Face rotateHalf(){
half = this.rotateRight();
half = half.rotateRight();
return half;
}
public int[][] getGrid(){
return (this.grid).clone();
}
public String toString(){
String str = "";
for (int i = 0; i<3;i++){
for (int j = 0; j<3; j++){
str += String.format("%02d",grid[i][j]);
}
}
String str1 = str.substring(0,6);
String str2 = str.substring(6,12);
String str3 = str.substring(12,18);
return str1+"\n"+str2+"\n"+str3;
}
}
但是,当我尝试运行以下命令时:
However, when I try to run the following:
int[][] g = f.getGrid();
g[1][1] = 9;
我希望f保持为
010203
040507
070809
但我最终得到了
010203
040906
070809
相反.即使我已经将该类声明为final,我的Face对象也不会保持不变吗?
instead. Is my Face object not made immutable even though I have already declared the class as final?
推荐答案
您需要在构造函数中创建输入grid
的防御性副本.
You need to make a defensive copy of the input grid
in the constructor.
此外,字段也应该为private
,类也应该为final
,尽管我怀疑最后两点不是造成问题的原因.
Also, the fields should be private
as well, and the class should be final
too, although I suspect those last two points are not the cause of your problem.
未测试:
public Face(int[][] grid){
int temp[][] = new int[ grid.length ][];
for( int i = 0; i < temp.length; i++ )
temp[i] = Arrays.copyOf( grid[i], grid[i].length );
this.grid = temp;
}
这篇关于即使我已经将Face类声明为final类,它似乎也不是一成不变的,该如何更正呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!