Java:长结果 = -1:无法从 int 转换为 long [英] Java: Long result = -1: cannot convert from int to long
问题描述
我正在使用 eclipse java ee 来执行 java 编程.
I'm using eclipse java ee to perform java programming.
我的一个函数中有以下代码行:
I had the following line of code in one of my functions:
Long result = -1;
我收到以下错误:
类型不匹配:无法从 int 转换为 Long
Type mismatch: cannot convert from int to Long
我不太明白为什么当我向变量添加数字时会出现此错误.
I can't quite understand why when i add a number to the variable it provides this error.
如何解决这个问题,为什么会发生?
How can this issue be resolved and why did it happen in the first place?
推荐答案
对象Long
和int
之间没有转换,所以需要从>长
.添加一个 L
使整数 -1
变成一个 long
(-1L
):
There is no conversion between the object Long
and int
so you need to make it from long
. Adding a L
makes the integer -1
into a long
(-1L
):
Long result = -1L;
但是有一个从 int
到 long
的转换,所以这是有效的:
However there is a conversion from int
a long
so this works:
long result = -1;
因此你也可以这样写:
Long result = (long) -1;
从原语(int
、long
等)转换为 Wrapper 对象(Integer
、Long
等)) 称为自动装箱,请在此处阅读更多信息.
Converting from a primitive (int
, long
etc) to a Wrapper object (Integer
, Long
etc) is called autoboxing, read more here.
这篇关于Java:长结果 = -1:无法从 int 转换为 long的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!