使用 int 与 Integer

2022-01-14 00:00:00 integer int java primitive

我遇到了一个类,它使用整数变量来捕获要在 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 方式对值进行装箱/拆箱.在适当的情况下使用 int ,除非您特别需要以 OO 方式使用它;在这种情况下,整数是合适的.

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 ) - 尽管可以编写这些版本提供与对象版本类似的功能的类.这包装类( Integer , Double 等)经常需要每当使用自省时(例如在反射 API 中).

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
  • 接受对象的方法(包括像 List<T> 这样的泛型类型)将隐式要求使用 Integer
  • 使用 Integer 对于低值(-128 到127)因为实习 - 使用 Integer.valueOf(int) 而不是新的整数(int)
  • 不要在整数类型中使用 ==!=
  • 当您需要表示没有值(null)
  • 注意将 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

相关文章