一个快速的问题:这段代码是否保证总是打印true
?
Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2);
布尔类型的装箱似乎总是导致相同的布尔对象,但我在JLS中没有找到太多关于装箱布尔相等性的信息。相反,它甚至似乎暗示装箱应该创建新对象,甚至可能导致OOM异常。
你有什么想法?
一个快速的问题:这段代码是否保证总是打印true
?
Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2);
装箱转换将原始类型表达式转换为相应的引用类型表达式。具体来说,以下九个转换称为装箱转换:
- 从类型
boolean
到类型Boolean
[...]
如果被装箱的值
p
是int类型的整数字面量,介于-128
和127
之间(§3.10.1),或boolean
字面量true
或false
(§3.10.3),或介于'\u0000'
和'\u007f'
之间的字符字面量(§3.10.4),那么让a
和b
分别成为p
的两个装箱转换的结果,则总是有a == b
。
这在实现上相对简单,如下:
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code true}.
*/
public static final Boolean TRUE = new Boolean(true);
/**
* The {@code Boolean} object corresponding to the primitive
* value {@code false}.
*/
public static final Boolean FALSE = new Boolean(false);
public static Boolean valueOf(boolean b) {
return (b ? TRUE : FALSE);
}
Boolean.TRUE == true
不能保证是正确的,对吧? - Oleg Mikheev是的。编译器会自动将此内容翻译为:
Boolean b1 = true;
转换为以下内容:
Boolean b1 = Boolean.valueOf(true);
这个方法总是返回两个常量之一,Boolean.TRUE
或 Boolean.FALSE
。
new Boolean(true)
不会等于其他装箱的布尔值。 - Louis Wasserman