Comparing Long object type with primitive int using ==

偶尔善良 提交于 2019-12-10 17:27:47

问题


I have a method that returns a Long object datatype via invocation of: resp.getResultCode(). I want to compare it HttpStatus.GONE.value() which actually just returns a primitive int value of 410. Would the Long unbox itself to properly compare with the int primitive?

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

回答1:


Here's the 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).

and

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

So the Long is unboxed to long. And numeric promotion is applied to int to make it a long. Then they are compared.

Consider that case where long would be "demoted" to an int, you'd have cases like this

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
}


来源:https://stackoverflow.com/questions/26761328/comparing-long-object-type-with-primitive-int-using

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!