Java 克隆数组以保留原始值以供将来使用

Java 克隆数组以保留原始值以供将来使用,java,arrays,clone,Java,Arrays,Clone,对于不同的对象顺序集,我有几个对象数组 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;

对于不同的对象顺序集,我有几个对象数组

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克隆的临时数组中的原始值,该数组应该保存我发送给该方法的原始数组——在本例中是第一行。问题是,它将所有内容恢复到currentArray,但不恢复到发送给方法的原始数组-优先


有没有办法让它更改发送给该方法的原始第一个数组?

在找不到解决方案后,我最终做了一个for循环:

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)
            for(int i=0; i<currentArray.length;i++)
                currentArray[i]=temp[i];
    }
}
而且。。。这对我有用!
你觉得怎么样?

currentArray[x]==currentArray[y];currentArray[y]==null;-这没什么用。您使用了==相等比较运算符,而不是=赋值运算符。@user2357112甚至无法编译,所以它可能不是OP实际拥有的。@MarkoTopolnik:哦,是的,您是对的。我忘了Java在语法上禁止在这样的位置使用无副作用的操作符。你能展示一下实际的方法吗?很难区分您在实际代码中犯了哪些错误,哪些错误是不相关的。在任何情况下,currentArray=temp.clone都不会修改任何阵列。它使currentArray变量指向一个新数组。如果要恢复对阵列的更改,我建议您跟踪所做的特定更改并撤消分配,或者在知道不会撤消更改之前不要进行更改。您也可以使用for循环或System.arraycopy将克隆复制到原始版本中,但这可能不是最好的方法。抱歉。原始代码当然使用=运算符,而不是==相等。我编辑了我的帖子。