如何在 Java 中将 Long 转换为 int?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5801431/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I cast a Long to an int in Java?
提问by Alex
Long x;
int y = (int) x;
Eclipse is marking this line with the error:
Eclipse 正在用错误标记这一行:
Can not cast Long to an int
不能将 Long 转换为 int
回答by Sean Patrick Floyd
Use primitive long
使用原语 long
long x = 23L;
int y = (int) x;
You can't cast an Object (Long is an Object) to a primitive, the only exception being the corresponding primitive / wrapper type through auto (un) boxing
您不能将对象(Long 是一个对象)转换为原始类型,唯一的例外是通过自动(取消)装箱获得相应的原始类型/包装类型
If you must convert a Long
to an int, use Long.intValue()
:
如果必须将 a 转换Long
为 int,请使用Long.intValue()
:
Long x = 23L;
int y = x.intValue();
But beware: you may be losing information! A Long
/ long
has 64 bit and can hold much more data than an Integer
/ int
(32 bit only)
但请注意:您可能会丢失信息!A Long
/long
有 64 位并且可以容纳比Integer
/多得多的数据int
(仅限 32 位)
回答by Ishtar
Long x
is an object.
Long x
是一个对象。
int y = x.intValue();
回答by Alex
int y = (int) (long) x;
is working.
工作中。