[英]How can I cast a Long to an int in Java?
Long x;
int y = (int) x;
Eclipse 将此行标记为错误:
不能将 Long 转换为 int
使用原始long
long x = 23L;
int y = (int) x;
您不能将 Object(Long 是一个对象)转换为原语,唯一的例外是通过自动(取消)装箱的相应原语/包装器类型
如果必须将Long
转换为 int,请使用Long.intValue()
:
Long x = 23L;
int y = x.intValue();
但请注意:您可能会丢失信息! Long
/ long
有 64 位,可以容纳比Integer
/ int
更多的数据(仅限 32 位)
Long x
是 object。
int y = x.intValue();
int y = (int) (long) x;
正在工作中。
Long x1 = 123L;
long x2 = 123L;
int y1 = Math.toIntExact(x1);
int y2 = Math.toIntExact(x2);
这种转换既适用于原始类型,也适用于非原始类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.