【发布时间】:2013-08-15 06:12:59
【问题描述】:
如何定义 java 中的链式赋值,考虑以下几点:
- 链式赋值和链式声明有区别吗?
- 有没有办法让引用类型重复语句而不是传递引用?
例如
Integer a, b = new Integer(4);
在JLS 15.26 Assignment Operators 中说
在运行时,赋值表达式的结果是赋值发生后变量的值。赋值表达式的结果本身并不是一个变量。
所以a == b 应该是真的。
有没有办法实现
Integer a = new Integer(4)
Integer b = new Integer(4)
在一行中,这样
a != b,因为 a 和 b 是不同的对象。
其他信息
问题已经回答了,但我觉得不够清楚,所以这里有一些代码 澄清一下。
Integer a = null, b = null, c = null;
System.out.println(a + " " + b + " " + c); // null null null
a = b = c = new Integer(5); // <-- chained assignment
System.out.println(a + " " + b + " " + c); // 5 5 5
System.out.println(a.equals(b)); // true
System.out.println(b.equals(c)); // true
System.out.println(a == b); // true
System.out.println(b == c); // true
【问题讨论】:
-
通常从 -128 到 127 的整数被缓存在内存中,所以在你的示例中你永远不会得到 a != b,但我明白你的意思。
-
@Pescis
a != b引用相等,而不是值相等。 -
我混错了
Integer a, b = new Integer(4);离开anull -
@Pescis:
new Integer将总是返回对新对象的引用。这不是拳击或使用Integer.valueOf。
标签: java variable-assignment assignment-operator