我遇到了一个类,它使用整数变量来捕获要在 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) ==
或 !=
int
for performance reasons List<T>
)
will implicitly require the use of Integer Integer
is relatively cheap for low values (-128 to
127) because of interning - use Integer.valueOf(int)
and not new
Integer(int) ==
or !=
with Integer types Integer
when you need to represent the
absence of a value (null)这篇关于使用 int 与 Integer的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!