arraylist的副本不断修改为原始值 [英] Copy of arraylist keeps getting modified to the values of the original

查看:232
本文介绍了arraylist的副本不断修改为原始值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个系统来保存和调用屏幕状态,这是我第一次搞砸这种东西,所以我不知道什么最好的方式去做这是但我目前存储所有的PreviewMonitor对象(约40左右)在数组列表内部。问题是,当我创建一个名为allPreviewMonitors的ArrayList副本存储我最终与一个ArrayList,随着原始元素更新不断变化的元素。它几乎就像我使用原始的ArrayList,事实上,它应该是一个完全不同的ArrayList与'冻结'版本的元素和它们的状态,当我创建的allPreviewMonitor的副本。为什么这种行为发生?

I'm working on a system for saving and recalling screen states, this is my first time messing with this kind of stuff so I'm not really sure what the best way to go about this is but I currently store all the "PreviewMonitor" objects (about 40 or so) inside of an array list. The problem is that when I create a copy of the ArrayList titled "allPreviewMonitors" to be stored I end up with an ArrayList with elements that are constantly changing as they original elements are updated. It's almost as if I'm working with the original ArrayList when in fact, it should be an entirely different ArrayList with a 'frozen' version of the elements and their states when I created the copy of allPreviewMonitors. Why is this behavior happening? If need be I can show code, but I'm not sure it's needed here.

推荐答案

您只需将对象引用复制到您的ArrayList。您需要复制对象本身。

You are only copying object references into your ArrayList. You need to copy the objects themselves.

在Java中,所有对象变量实际上是引用变量。所以代码:

In Java, all object variables are actually reference variables. So the code:

Myclass myObject = new Myclass();
Myclass otherObject = myObject;

创建一个Myclass对象,并在引用变量 myObject 。然后创建一个新的引用变量 otherObject ,引用数据(例如内存地址)从 myObject code> otherObject 。这些现在指的是内存中的同一个对象。此时,行

creates a Myclass object and stores a reference to that Myclass object in the reference variable myObject. It then creates a new reference variable otherObject and the reference data (eg a memory address) is copied from myObject to otherObject. These now refer to the same object in memory. At this point, the line

myObject.myMethod();

otherObject.myMethod();

在ArrayList中获得的是对同一对象的不同引用。
你想要的是以下之一:

What you are getting in your ArrayList are different references to the same objects. What you want is one of the following:

Myclass otherObject = myObject.clone(); // use the clone function
// OR
Myclass otherObject = new Myclass(myObject); // use a copy constructor



如果使用 clone()或复制构造函数,您的ArrayList将包含对相同副本的引用,而不是对相同副本的引用。

If you put your objects into the ArrayList using clone() or a copy constructor, your ArrayList will contain references to identical copies, rather than references to the same copies.

指出,只是将引用的副本称为浅拷贝,而将引用的对象的副本称为深拷贝

As others have pointed out, just making copies of the references is called a 'shallow copy', while making copies of the objects that are referred to is called a 'deep copy'

这篇关于arraylist的副本不断修改为原始值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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