我意识到这是一个新手问题,但我似乎无法理解为什么我的代码会像现在这样工作。
我正在编写一个程序,我必须逐段反转数组的值(例如,{ {1,1}, {-1,1} }
将是{ {-1,-1}, {1,-1} }
。由于我必须多次执行此操作,因此我创建了一个抽象类,public abstract class GenericMethods
并定义了一个静态方法,以使其更快:
public static int[][] invert2DIntArray (int[][] inverted2DIntArray)
{
if (inverted2DIntArray != null)
{
for (int i=0; i < inverted2DIntArray.length; i++)
{
for (int j=0; j < inverted2DIntArray[i].length; j++)
{
inverted2DIntArray[i][j] *= -1;
}
}
return inverted2DIntArray;
}
else
{
return null;
}
}
(包括 null 检查,因为有时,它会得到一个 null 值作为输入。)
现在,我有一个类,它具有以下成员:private int[][] possibleCaptureMoves
。我还写了一个get方法,来获取这个成员:
public int[][] getPossibleCaptureMoves()
{
if (this.getPlayerType() == PlayerType.BLACK)
{
return GenericMethods.invert2DIntArray(possibleCaptureMoves);
}
else
{
return possibleCaptureMoves;
}
return possibleCaptureMoves;
}
我在这里想做的是,如果对象的玩家类型是黑色,它会返回反转的成员,但不会修改成员本身。因此,假设成员是 { {2,0}, {3,0} }
,并且玩家类型是 BLACK,它会返回 { {-2,0}, { -3,0} }
,但 possibleCaptureMoves
将保持原样,{ {2,0}, {3,0} }
。相反,这会返回 { {-2,0}, {-3,0} }
,但也会将成员修改为此 { {-2,0}, {-3, 0} }
值,而不是保持原样。
我做错了什么?抱歉,我意识到这完全是菜鸟错误,但我就是不明白为什么它会修改原始成员。
提前致谢,祝您愉快
最佳答案
数组是对象,因此,每当任何方法对它们起作用时,如果它们是参数,则原始值都会更改。
您需要创建数组的副本。
int copy[][] = new int[possibleCaptureMoves.length][possibleCaptureMoves[0].length];
for(int i=0; i<copy.length; i++)
{
for(int j=0; j<copy[i].length; j++)
{
copy[i][j] = possibleCaptureMoves[i][j];
}
}
return GenericMethods.invert2DIntArray(copy);
关于java - 如何使方法不修改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36768980/