問題描述
我遇到了一個類,它使用整數變量來捕獲要在 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 - useInteger.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 與 Integer的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!