Sometimes I see API’s using long
or Long
or int
or Integer
, and I can’t figure how the decision is made for that ?
我什么时候应该选择什么?
原文由 I know how to tick the V 发布,翻译遵循 CC BY-SA 4.0 许可协议
Sometimes I see API’s using long
or Long
or int
or Integer
, and I can’t figure how the decision is made for that ?
我什么时候应该选择什么?
原文由 I know how to tick the V 发布,翻译遵循 CC BY-SA 4.0 许可协议
int
。int
的范围太小,使用 long
long
的范围太小,使用 BigInteger
Collection
,处理 null
,…)使用 Integer
/ Long
代替原文由 Joachim Sauer 发布,翻译遵循 CC BY-SA 3.0 许可协议
8 回答6.4k 阅读
1 回答4.1k 阅读✓ 已解决
3 回答2.3k 阅读✓ 已解决
2 回答3.2k 阅读
2 回答3.9k 阅读
1 回答2.2k 阅读✓ 已解决
3 回答1.6k 阅读✓ 已解决
Long
is theObject
form oflong
, andInteger
is the object form ofint
.long
使用 64 位。int
使用 32 位,因此最多只能容纳 ±20 亿(-2 31到 +2 31 -1)的数字。You should use
long
andint
, except where you need to make use of methods inherited fromObject
, such ashashcode
.Java.util.collections
methods usually use the boxed (Object
-wrapped) versions, because they need to work for anyObject
, and a primitive type, likeint
或long
,不是Object
。Another difference is that
long
andint
are pass-by-value , whereasLong
andInteger
are pass-by-reference value ,像所有非原始 Java 类型一样。因此,如果可以修改Long
或Integer
(不是,它们在不使用 JNI 代码的情况下是不可变的),还有另一个理由使用另一个。最后一个区别是
Long
或Integer
可能是null
。