快速提问:是否保证此代码始终显示为真?
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
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。