简体   繁体   English

在Java中将int常量分配给长包装类

[英]Assigning an int literal to a long wrapper class in java

Why is there a compilation error with Long l = 3 and not with Long l = 3L ? 为什么在Long l = 3而不是Long l = 3L出现编译错误?

The primitive data type long accepts both 3 and 3l . 原始数据类型long接受33l I understand that 3 is an int literal - but it can't be assigned to a Long wrapper object? 我知道3是一个int常量,但是不能将其分配给Long包装器对象吗? int is only 32 bits shouldn't it fit in a 64 bit integer type? int只有32位,难道不适合64位整数类型吗?

Because there isn't an int to Long widening and autoboxing conversion, autoboxing converts from long to Long (but first the value must be widened from an int to a long ). 因为没有一个intLong加宽自动装箱转换,自动装箱从转换longLong (但第一值必须从一个加宽 intlong )。 You could do 3L as you have, or 您可以按照自己的3L3L ,或者

Long l = Long.valueOf(3);

or 要么

Long l = (long) 3;

For additional answer: 有关其他答案:

3L is equals to (long)3 --> parse it to 3L as it is a long literal 3L等于(long)3 >将其解析为3L,因为它是长整数

3 is a integer literal 3是整数文字

3L is a long literal 3L是长字面量

in a nutshell, they are different from each other that's why you need to parse int to long or vice versa. 简而言之,它们彼此不同,因此您需要将int解析为long,反之亦然。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM