使用int vs Integer [英] Using int vs Integer

查看:118
本文介绍了使用int vs Integer的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个使用Integer变量的类来捕获要在for循环中使用的大小。这是一种好的做法还是应该使用int原始数据类型?

I came across a class using Integer variables to capture size to be used in a for loop. Is this good practice or should we use the int primitive data type?

Integer size = something.getFields().size();
for (Integer j = 0; j < size - 1; ++j) 


推荐答案

提供了Integer类,以便可以以纯OO方式对值进行装箱/取消装箱。除非您特别需要以OO方式使用它,否则请在适当的地方使用int;在这种情况下,整数是合适的。

the Integer class is provided so that values can be boxed/unboxed in a pure OO manner. use int where appropriate unless you specifically need to use it in an OO way; in which case Integer is appropriate.

Java Int vs Integer


然而,这里有很多不同的东西。 int是一个数字; an> Integer是一个可以引用包含数字的对象的指针。

However, very different things are going on under the covers here. An int is a number; an > Integer is a pointer that can reference an object that contains a number.

...

int不是对象,不能传递给任何需要
对象的方法。一个常见的情况是使用提供的集合类(
List,Map,Set) - 尽管可以编写这些
类的版本,这些类提供与对象版本类似的功能。每当使用内省时(例如在反射API中),
包装类(Integer,Double等)经常需要

An int is not an object and cannot passed to any method that requires objects. A common case is in using the provided collection classes ( List , Map , Set ) - though it is possible to write versions of these classes that provide similar capabilities to the object versions. The wrapper classes ( Integer , Double , etc) are frequently required whenever introspection is used (such as in the reflection API).

更好地描述何时使用一个与另一个:

A better description of when to use one vs. the other:

在int和Integer之间选择

Choosing between int and Integer


我将在进入
详细信息之前先了解这些类型的使用方法。

I'll start with how these types should be used before going into detail on why.


  • 出于性能原因首选 int

  • 获取对象的方法(包括等泛型类型列表< T>
    将隐式要求使用Integer

  • 使用整数因为实习而对低值(-128到
    127)相对便宜 - 使用 Integer.valueOf(int)而不是新的
    整数(int )

  • 不要使用 == != 使用整数类型

  • 当你需要r时,考虑使用 Integer 表示
    缺少值(null)

  • 注意取消装箱整数值为int且值为空值

  • Prefer int for performance reasons
  • Methods that take objects (including generic types like List<T>) will implicitly require the use of Integer
  • Use of Integer is relatively cheap for low values (-128 to 127) because of interning - use Integer.valueOf(int) and not new Integer(int)
  • Do not use == or != with Integer types
  • Consider using Integer when you need to represent the absence of a value (null)
  • Beware unboxing Integer values to int with null values

这篇关于使用int vs Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆