ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java – 盒装布尔值的等价

2019-07-16 08:59:52  阅读:265  来源: 互联网

标签:java autoboxing primitive


快速提问:是否保证此代码始终显示为真?

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那样

/**
 * 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. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有