加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 盒装布尔值的等价

发布时间:2020-12-15 04:45:17 所属栏目:Java 来源:网络整理
导读:快速提问:是否保证此代码始终显示为真? Boolean b1 = true;Boolean b2 = true;System.out.println(b1 == b2); 拳击布尔似乎总是导致相同的布尔对象,但我找不到太多关于JLS中的盒装布尔相等的信息.相反,它甚至似乎暗示拳击应该创建新对象,甚至可能导致OOM异
快速提问:是否保证此代码始终显示为真?

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读