比较在Java中相互引用的对象

时间:2013-04-28 10:00:30

标签: java object compare refer

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相同 - 根据给出的参考值改变。

为什么这个对象只引用另一个对象"工作"用户定义的对象,而不是整数,字符串等?



谢谢大家的答案 - 现在我明白了!

4 个答案:

答案 0 :(得分:3)

StringInteger对象在Java中是不可变的。执行:ii += 1k += "tring"时,您将创建新对象。变量jjl指向旧对象。这就是你看到不同价值观的原因。

答案 1 :(得分:0)

此行为与用户定义的对象与内部无关,但事实上,“整数”和“字符串”(以及所有其他原始包装器)对象的处理非常特殊。整数只是一个原始整数的“包装器”,因此它的行为不是真正的“参考类型”。所有这些包装器对象都是不可变的 - 对整数的引用永远不会有另一个值。

侧面说明:如果需要,这些包装器对象会自动转换为基本类型,因此它们在一般使用中速度较慢。它们的好处是,它们可以为空,有时很好。

答案 2 :(得分:0)

这与+=运营商的工作有关。

您真正要做的是在致电+=

时重新分配价值
Integer i = 1;
Integer j = i;
i = i + 1;

所以现在i指向的另一个Integer等于2j仍然指向原始的Integer等于1

String示例也是如此。

在您的对象案例中,您不会更改指针,而是更改对象的内部状态。因此,person1person2都指向相同的Person

如果你做了

Person person1 = new Person("Alice");
Person person2 = person1;
person1 = new Person("Bob");

然后很明显,person1现在是不同的 Person

答案 3 :(得分:0)

1)字符串和包装器(Integer,Long ..)是不可变对象和 2)Person是一个可变对象,你修改了它的属性,因为person1和person2指向同一个引用,所以在两个对象中都应用了这些更改。

(不可变 - 一旦你创造了你就无法改变它的状态)