Long vs Integer,long vs int,什么时候使用?

新手上路,请多包涵

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 许可协议

阅读 787
2 个回答

Long is the Object form of long , and Integer is the object form of int .

long 使用 64 位int 使用 32 位,因此最多只能容纳 ±20 亿(-2 31到 +2 31 -1)的数字。

You should use long and int , except where you need to make use of methods inherited from Object , such as hashcode . Java.util.collections methods usually use the boxed ( Object -wrapped) versions, because they need to work for any Object , and a primitive type, like intlong ,不是 Object

Another difference is that long and int are pass-by-value , whereas Long and Integer are pass-by-reference value ,像所有非原始 Java 类型一样。因此,如果可以修改 LongInteger (不是,它们在不使用 JNI 代码的情况下是不可变的),还有另一个理由使用另一个。

最后一个区别是 LongInteger 可能是 null

原文由 Borealid 发布,翻译遵循 CC BY-SA 3.0 许可协议

  • 默认情况下,在保存数字时使用 int
  • 如果 int 的范围太小,使用 long
  • 如果 long 的范围太小,使用 BigInteger
  • 如果您需要将数字作为对象处理(例如将它们放入 Collection ,处理 null ,…)使用 Integer / Long 代替

原文由 Joachim Sauer 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题