【发布时间】:2013-12-30 14:16:06
【问题描述】:
我有几个对象数组用于不同的对象顺序集。
public class MyObject extends Location{
String color;
int location;
}
我在一个单独的类中有以下数组:
public class Location{
MyObject[] first; /// initiated in main as new MyObject[20]; and holding values...
MyObject[] second;
MyObject[] third;
MyObject[] temp; /// to be used later to hold the original array within a method
在类位置中,我将其中一个数组(不包括 temp)发送到另一个方法:
makeMove(first//for example//, blah blah blah)
public boolean makeMove(MyObject[] currentArray, blah blah blah){
temp = first.clone(); // I clone in order to save the original values in case the next method == false
if(isLegal(currentArray, blah, blah){
currentArray[x]=currentArray[y]; currentArray[y]=null; // This does change the values in the original array "first".
if(anotherCheck(currentArray, blah)
currentArray = temp.clone(); // restores cuurentArray values but not "first".
}
}
最后一行应该返回存储在我从 currentArray 克隆的“temp”数组中的原始值(它应该保存我发送给方法的原始数组 - 在本例中为“first”)。问题是它将所有内容恢复为“currentArray”,但没有恢复到发送给方法的原始数组 - “first”。
有没有办法让它改变发送给方法的原始“第一个”数组?
【问题讨论】:
-
currentArray[x]==currentArray[y]; currentArray[y]==null;- 这没有任何作用。您使用了==相等比较运算符,而不是=赋值运算符。 -
@user2357112 这甚至无法编译,所以它可能不是 OP 实际拥有的。
-
@MarkoTopolnik:哦,是的,你是对的。我忘记了 Java 在语法上禁止在这些位置使用无副作用的运算符。
-
你能展示一下实际的方法吗?很难分辨你在真实代码中犯了哪些错误,哪些错误是无关紧要的。在任何情况下,
currentArray = temp.clone()都不会修改任何数组。它使currentArray变量指向一个新数组。如果您想恢复对数组的更改,我建议您跟踪所做的特定更改并撤消分配,或者在您知道不会撤消它们之前不进行更改。您也可以使用 for 循环或 System.arraycopy 将克隆复制到原始文件中,但这可能不是最好的方法。 -
对不起。原始代码当然是使用“=”运算符而不是“==”相等。我编辑了我的帖子。