Java:长结果 = -1:无法从 int 转换为 long [英] Java: Long result = -1: cannot convert from int to long

查看:58
本文介绍了Java:长结果 = -1:无法从 int 转换为 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?

推荐答案

对象Longint之间没有转换,所以需要从>长.添加一个 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;

但是有一个从 intlong 的转换,所以这是有效的:

However there is a conversion from int a long so this works:

long result = -1;

因此你也可以这样写:

Long result = (long) -1;

从原语(intlong 等)转换为 Wrapper 对象(IntegerLong 等)) 称为自动装箱,请在此处阅读更多信息.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆