盒装布尔值的相等性

Equality of boxed boolean

小问题:是否保证此代码始终打印 true

Boolean b1 = true;
Boolean b2 = true;
System.out.println(b1 == b2);

布尔值的装箱似乎总是产生相同的布尔对象,但我在 JLS 中找不到太多关于装箱布尔相等性的信息。相反,它甚至似乎暗示装箱应该创建新对象,甚至可能导致 OOM 异常。

你有什么想法?

来自Java Language Specification on Boxing Conversion

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type. Specifically, the following nine conversions are called the boxing conversions:

  • From type boolean to type Boolean

[...]

If the value p being boxed is an integer literal of type int between -128 and 127 inclusive (§3.10.1), or the boolean literal true or false (§3.10.3), or a character literal between '\u0000' and '\u007f' inclusive (§3.10.4), then let a and b be the results of any two boxing conversions of p. It is always the case that a == b.

这个比较简单implemented as

/**
 * 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 b1 = true;

进入这个:

Boolean b1 = Boolean.valueOf(true);

这总是 returns 两个常量之一 Boolean.TRUEBoolean.FALSE.