java – 盒装布尔值的等价
作者:互联网
快速提问:是否保证此代码始终显示为真?
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 typeBoolean
[…]
If the value
p
being boxed is an integer literal of typeint
between
-128
and127
inclusive (§3.10.1), or theboolean
literaltrue
orfalse
(§3.10.3), or a character literal between'\u0000'
and'\u007f'
inclusive (§3.10.4), then leta
andb
be the results of any two boxing
conversions ofp
. It is always the case thata == b
.
这相对简单就像implemented那样
/**
* 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);
}
标签:java,autoboxing,primitive 来源: https://codeday.me/bug/20190716/1476523.html