使用Object.clone()的错误 [英] Bug in using Object.clone()

查看:68
本文介绍了使用Object.clone()的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一个场景:



我在主类中定义了 int [] [] 变量。 int [] [] matrix1 = new int [10] [10] 我给它一些值。然后,我调用一个方法,然后将此变量作为参数发送给该方法。作为它发送的对象是通过引用而不是按值,因此在方法内部,因为我必须更改matrix1包含的值,但是在该对象从方法返回后不影响该对象,因此我将其克隆为:

  private void myMethod(int [] [] matrix1)
{
int [] [] matrix1Clone = matrix1 。克隆();
//接下来我要对matrix1进行一些更改复制
......
}

但是问题是我对matrix1Clone所做的更改也发生在matrix1中。因此它并没有真正创建matrix1对象的克隆,但是两个变量都指向同一个对象。



这是为什么?我似乎无法弄清楚。为什么克隆方法无效?



如果您需要更多信息,请询问。但是我担心这是真的,不能真正给您更多,但是也许我可以尝试。



我可能会丢失一些东西,但是我不能找出什么...



谢谢。



编辑



抱歉,打错了字。迟到了,我很累。我确实在使用克隆方法,这就是为什么我困惑的原因,因为它不起作用:(。

解决方案

尝试使用clone() http: //docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone%28%29

  private void myMethod(int [] [] matrix1)
{
int [] [] matrix1Clone = matrix1.clone();
}

或使用循环复制所有值



编辑:对于clone()的Api表示应该返回对象的副本,但是行为可能会有所不同,具体取决于要克隆哪个对象。尝试遍历数组作为替代方案。由于它是二维数组,因此需要嵌套循环:

  for(int i = 0; i 

for(int j = 0 ; j< old [i] .length; j ++)
old [i] [j] = copy [i] [j];

其中旧的是原始数组,而副本就是副本


I have the next scenario:

I define an int[][] variable in my main class. int[][] matrix1 = new int[10][10] and i give it some values. I then call a method and i send this variable as a parameter to that method. Being an object it sends is by reference not by value, so inside the method, because i have to change the values contained by matrix1 but not affect the object after it returns from the method, i make a clone of it like so:

private void myMethod( int[][] matrix1 )
{
    int[][] matrix1Clone = matrix1.clone();
    //And next i do some changes to matrix1Clone
    ......
}

But the problem is that the changes i do to matrix1Clone also happen in matrix1. So it hasn't really created a clone of matrix1 object, but both variables point to the same object.

Why is this? I can't seem to figure it out. Why doesn't clone method work?

If you need more info, please ask. But i'm afraid this is about it, can't really give you more, but maybe i could try.

I might be missing something, but i can't figure out what...

Thanks.

EDIT

Sorry, made a typo. It's late hre and i'm tired. I'm using clone method indeed, that's why i'm confused as it's not working :(.

解决方案

Try clone it using clone() http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Object.html#clone%28%29

private void myMethod( int[][] matrix1 )
{
    int[][] matrix1Clone = matrix1.clone();
}

or, copy all of the values using a loop

EDIT: Api for clone() says it should return a copy of the object, but behavior might be different depending on which object's beeing cloned. Try iterating over the array as an alternative. Since it's a 2d array, you need a nested loop:

for(int i=0; i<old.length; i++)
  for(int j=0; j<old[i].length; j++)
    old[i][j]=copy[i][j];

where old is the "original array" and copy is the copy

这篇关于使用Object.clone()的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆