gpt4 book ai didi

java - 使用 == 将 Long 对象类型与原始 int 进行比较

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

我有一个通过调用返回 Long 对象数据类型的方法:resp.getResultCode()。我想比较一下 HttpStatus.GONE.value(),它实际上只是返回 410 的原始 int 值。 Long 是否会自行拆箱以与 int 原语进行正确比较?

if(resp.getResultCode() == HttpStatus.GONE.value()){
// code inside..
}

最佳答案

这是 JLS explanation

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

If the promoted type of the operands is int or long, then an integer equality test is performed.

因此 Long 被拆箱为 long。并将数字提升应用于 int 以使其成为 long。然后将它们进行比较。

考虑 long 将被“降级”为 int 的情况,您会遇到这样的情况

public static void main(String[] args) throws Exception {
long lvalue = 1234567891011L;
int ivalue = 1912277059;
System.out.println(lvalue == ivalue); // false
System.out.println((int) lvalue == ivalue); // true, but shouldn't
}

关于java - 使用 == 将 Long 对象类型与原始 int 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26761328/

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