gpt4 book ai didi

java - 使用 == 运算符进行原始和对象比较

转载 作者:搜寻专家 更新时间:2023-11-01 01:50:39 26 4
gpt4 key购买 nike

我想知道下一个片段的内部 Java 行为是什么:

Long a = 123L;
long b = 123;
System.out.println("a equals b?: " + (a == b));

结果是 true 尽管比较两个 Long 对象将是 false(因为它比较它们的引用)。它是 Java 将 Long 对象转换为其原始值,因为检测到针对另一个原始对象的 == 运算符?

最佳答案

It is Java converting Long object into its primitive value because detects == operator against another primitive object?

是的。其中一个操作数是原始类型,另一个操作数可通过拆箱转换为原始类型。

JLS section 15.21.1说(强调我的):

If the operands of an equality operator are both of numeric type, or one is of numeric type and the other is convertible (§5.1.8) to numeric type, binary numeric promotion is performed on the operands (§5.6.2).

Note that binary numeric promotion performs value set conversion (§5.1.13) and may perform unboxing conversion (§5.1.8).

此外,重要的是要注意引用相等性仅在两个操作数都是对象时才执行。金力士section 15.21.3说:

If the operands of an equality operator are both of either reference type or the null type, then the operation is object equality.

关于java - 使用 == 运算符进行原始和对象比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34308440/

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