gpt4 book ai didi

java - 字符等于字符在 Java 中是自动装箱还是拆箱?

转载 作者:行者123 更新时间:2023-12-01 09:49:46 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





When using == for a primitive and a boxed value, is autoboxing done, or is unboxing done

(3 个回答)


4年前关闭。




我正在考虑这个简单的代码:

Character s = 'n';
System.out.println(s == 'y');
System.out.println(s.equals('y'));

s = 'y';
System.out.println(s == 'y');
System.out.println(s.equals('y'));

结果
false
false
true
true

所以结果很好,但是,这种比较是如何工作的? Character 对象是取消装箱为字符还是聊天自动装箱为字符?

最佳答案

== 的情况下测试,Java Language Specification, Section 15.21 ,说明 Character已拆箱为 char (数字类型)。

The equality operators may be used to compare two operands that are convertible (§5.1.8) to numeric type, or two operands of type boolean or Boolean, or two operands that are each of either reference type or the null type.



在 §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).



equals()的情况下, char值被装箱为 Character , 因为参数是 equals()需要是引用类型。

关于java - 字符等于字符在 Java 中是自动装箱还是拆箱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40736019/

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