简体   繁体   English

在java中更新对象的问题

[英]Questions with updating objects in java

If I have an instance of an object, and within that object is a variable that holds the data of another object. 如果我有一个对象的实例,并且该对象内是一个保存另一个对象的数据的变量。 If I ever update the second object will the copy of that object be updated as well or do I need to simultaneously update all copies of said object. 如果我更新第二个对象,那么该对象的副本也会更新,或者我是否需要同时更新所述对象的所有副本。

For example: 例如:

public class Object()
{
    int x = xValue;
    Object linked = saidObject;
}

public class doStuff()
{
   saidObject.x++;
   if(linked.equals(saidObject))
       return true;
}

will this code (not compilable obviously just fill in blanks) return true? 这段代码(不可编译显然只是填空)返回true?

By doing: 通过做:

Object linked = saidObject;

you are not copying the object, just creating another pointer to it, it means you have two different pointers that point to the same object. 你没有复制对象,只是创建另一个指向它的指针,这意味着你有两个不同的指针指向同一个对象。

copying or cloning an object can be useful in some cases but its not the usual case. 在某些情况下复制或克隆对象可能很有用,但这不是通常的情况。

if(linked.equals(saidObject)) will return true as the two variables do point to the same object. if(linked.equals(saidObject))将返回true,因为两个变量确实指向同一个对象。

In Java all variables and fields are references to an actual Object that lives somewhere in memory. 在Java中,所有变量和字段都是对存在于内存中的实际Object的引用。

When you assign one variable to another, it's like copying the address of the object so that they both point to the same object in memory. 将一个变量分配给另一个变量时,就像复制对象的地址一样,它们都指向内存中的同一个对象。

eg 例如

Object a = new Object();  // this actually creates the Object in memory
Object b = a;             // this copies the reference to Object from a to b
// At this point, a and b point to exactly the same object in memory. Therefore ...
a.equals(b);              // returns true.

In fact a == b returns true too, which is a better way of comparing for this case as == compares if two variables point to the same object (they do), whereas equals() often compares by value, which is unnecessary here. 实际上a == b返回true,这是比较这种情况的更好方法,因为==比较两个变量是否指向同一个对象(它们),而equals()通常按值进行比较,这在此不必要。

It doesn't matter if b is actually a field within a (eg class Obj { Obj b; }; Obj a = new Obj(); ab = a; ) and it points to the same type of object, the principle is the same: a = b means they point to same object, nothing new is created. 如果不要紧b实际上是中的一个字段a (例如class Obj { Obj b; }; Obj a = new Obj(); ab = a;和其指向同一类型的对象,其原理是相同: a = b表示它们指向同一个对象,不会创建任何新对象。

An object instance is itself and is distinct from every other instance. 对象实例本身并且与每个其他实例不同。

That is, mutating an object (by reassigning a field) someplace modifies it everywhere .. as, well, it is what it is. 也就是说,改变一个对象(通过重新分配一个字段) 某处可以在任何 地方修改它......因为它就是它的本质。 Likewise, mutating a different object .. is, well, changing a different object. 同样,改变一个不同的对象..也就是说,改变一个不同的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM