下面的代码给出了错误(使用 IDEA),而我认为它不应该出现错误。
Long[] a = {0L, 0L};
Long[] b = {1L, 1L};
if((a[0] + a[1]).equals(b[1]))
System.out.println("Equal");
说cannot resolve method equals(java.lang.Long)
。但它与 if(a[0].equals(b[0]))
配合得很好。我认为加号运算符会返回一个 Long 对象。
为什么它看起来没有返回 Long
对象,以及我们如何使用 Long c = a[0] + a[1]
如果它不返回 Long 对象?或者为什么我们不能使用 equals
就这样?
最佳答案
Why does it seem like it doesn't return a
Long
object?
15.18.2. Additive Operators (+ and -) for Numeric Types 告诉我们:
Binary numeric promotion is performed on the operands.
The type of an additive expression on numeric operands is the promoted type of its operands.
和5.6.2. Binary Numeric Promotion 告诉我们:
If any operand is of a reference type, it is subjected to unboxing conversion.
这意味着 Long + Long
的结果是 long
,并且我们无法调用基本类型上的方法。
And how are we able to use
Long c = a[0] + a[1]
if it doesn't return aLong
object?
对于 Long c = a[0] + a[1]
,long
由赋值框起来。
关于java - 无法解析方法 equals(java.lang.Long),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152870/