0
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

4 回答 4

3

StringInteger对象在 Java 中是不可变的。当您这样做时:ii += 1或者k += "tring"您创建新对象。变量jjl指向旧对象。这就是为什么你会看到不同的价值观。

于 2013-04-28T10:11:01.050 回答
0

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

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

于 2013-04-28T10:10:58.993 回答
0

这与+=操作员的工作有关。

你真正在做的是在你打电话时重新分配价值+=

Integer i = 1;
Integer j = i;
i = i + 1;

所以 nowi指向另一个Integerequal to2并且j仍然指向原来的Integerequal to 1

你的String例子也是如此。

在您的对象情况下,您不会更改指针,而是更改对象的内部状态。因此两者person1person2指向相同Person

如果你做了

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

那么现在应该很明显person1不同 Person了。

于 2013-04-28T10:11:06.787 回答
0

1)Strings 和 Wrappers(Integer, Long..) 是不可变对象,2)Person 是可变对象,您修改了它的属性,并且由于 person1 和 person2 指向相同的引用,因此更改适用于两个对象。

(不可变的——一旦你创建了你就不能改变它的状态)

于 2013-04-28T10:16:04.777 回答