[英]Comparing Objects which refer to each other in Java
int i = 0;
int j = i;
System.out.println("initial int: " + j); // 0
Integer ii = new Integer(0);
Integer jj = ii;
System.out.println("initial Integer: " + jj); // 0
String k = new String("s");
String l = k;
System.out.println("initial String: " + l); // "s"
Person person1 = new Person("Furlando"); // from constructor -> publ. instance var. 'name'
Person person2 = person1;
System.out.println("initial Person: " + person2.name); // "Furlando"
/*--------------------*/
System.out.println();
/*--------------------*/
i += 1;
System.out.print("added 1 to int: [" + i);
System.out.println("], and primitive which also \"refers\" to that (has a copy, actually), has a value of: [" + j + "]");
ii += 1;
System.out.print("added 1 to Integer object: [" + ii);
System.out.println("], and object which also refers to that, has a value of: [" + jj + "]");
k += "tring";
System.out.print("added \"s\" to String object: [" + k);
System.out.println("], and object which also refers to that, has a value of: [" + l + "]");
person1.name = "Kitty";
System.out.print("changed instance variable in Person object to: [" + person1.name);
System.out.println("], and object which also refers to that, has a value of: [" + person2.name + "]");
/* [COMPILER OUTPUT]
initial int: 0
initial Integer: 0
initial String: s
initial Person: Furlando
A) added 1 to int: [1], and primitive which also "refers" to that (has a copy, actually), has a value of: [0]
B) added 1 to Integer object: [1], and object which also refers to that, has a value of: [0]
C) added "s" to String object: [string], and object which also refers to that, has a value of: [s]
D) changed instance variable in Person object to: [Kitty], and object which also refers to that, has a value of: [Kitty]
*/
我了解A,我们那里有一个原始的; 没有参考。 副本。
我希望B和C的行为与D相同-根据给定的参考进行更改。
为什么这个对另一个对象的对象引用只能与用户定义的对象一起使用,而不能与整数,字符串等一起使用?
String
和Integer
对象在Java中是不可变的。 当您这样做时: ii += 1
或k += "tring"
您将创建新对象。 变量jj
和l
指向旧对象。 这就是为什么您看到不同的值。
此行为与用户定义的对象而不是内部的对象有关,而是有关“整数”和“字符串”(以及所有其他原始包装器)对象的处理非常特殊的事实。 整数只是围绕原始整数的“包装器”,因此它的行为并不是真正的“引用类型”。 所有这些包装器对象都实现为不可变的-对Integer的相同引用将永远不会有另一个值。
附带说明:那些包装器对象在必要时会自动转换为基本类型,因此,它们的通用用法较慢。 它们的好处是,它们可以为null,这有时很好。
这与+=
运算符的工作有关。
您真正在做什么是在调用+=
时重新分配值
Integer i = 1;
Integer j = i;
i = i + 1;
因此,现在i
指向另一个等于2
Integer
,而j
仍指向原始等于1
Integer
。
您的String
示例也是如此。
在您的对象情况下,您无需更改指针,而可以更改对象的内部状态。 因此person1
和person2
指向同一个Person
。
如果你做了
Person person1 = new Person("Alice");
Person person2 = person1;
person1 = new Person("Bob");
显然, person1
现在是另一个 Person
。
1)String和Wrappers(Integer,Long ..)是不可变的对象,而2)Person是可变对象,并且您修改了它的属性,并且由于person1和person2指向相同的引用,因此更改应用于两个对象。
(不可变-创建后就无法更改其状态)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.