gpt4 book ai didi

java - 盒装 boolean 值的相等性

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:38:30 25 4
gpt4 key购买 nike

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

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

boolean 值的装箱似乎总是产生相同的 boolean 对象,但我在 JLS 中找不到太多关于装箱 boolean 相等性的信息。相反,它甚至似乎暗示装箱应该创建新对象,甚至可能导致 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 - 盒装 boolean 值的相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28636738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com