問題描述
例如為什么你可以這樣做:
For example why can you do:
int n = 9;
但不是:
Integer n = 9;
你可以這樣做:
Integer.parseInt("1");
但不是:
int.parseInt("1");
推薦答案
int
是原始類型.int
類型的變量存儲您要表示的整數的實際二進制值.int.parseInt("1")
沒有意義,因為 int
不是 一個類,因此沒有任何方法.
int
is a primitive type. Variables of type int
store the actual binary value for the integer you want to represent. int.parseInt("1")
doesn't make sense because int
is not a class and therefore doesn't have any methods.
Integer
是一個類,與 Java 語言中的任何其他類沒有什么不同.Integer
類型的變量將 references 存儲到 Integer
對象,就像任何其他引用(對象)類型一樣.Integer.parseInt("1")
是對 Integer
類的靜態方法 parseInt
的調用(注意這個方法實際上返回一個 int
而不是 Integer
).
Integer
is a class, no different from any other in the Java language. Variables of type Integer
store references to Integer
objects, just as with any other reference (object) type. Integer.parseInt("1")
is a call to the static method parseInt
from class Integer
(note that this method actually returns an int
and not an Integer
).
更具體地說,Integer
是一個具有 int
類型的單個字段的類.此類用于需要將 int
視為任何其他對象的情況,例如在泛型類型或需要可空性的情況下.
To be more specific, Integer
is a class with a single field of type int
. This class is used where you need an int
to be treated like any other object, such as in generic types or situations where you need nullability.
請注意,Java 中的每個原始類型都有一個等效的 wrapper 類:
Note that every primitive type in Java has an equivalent wrapper class:
byte
有Byte
short
有short
int
有Integer
long
有Long
boolean
有Boolean
char
有Character
float
有Float
double
有Double
byte
hasByte
short
hasShort
int
hasInteger
long
hasLong
boolean
hasBoolean
char
hasCharacter
float
hasFloat
double
hasDouble
包裝類繼承自 Object 類,而原始類不繼承.所以它可以用在帶有對象引用或泛型的集合中.
Wrapper classes inherit from Object class, and primitive don't. So it can be used in collections with Object reference or with Generics.
從 java 5 開始,我們有了自動裝箱,原始類和包裝類之間的轉換是自動完成的.但是要小心,因為這可能會引入細微的錯誤和性能問題;明確說明轉化永遠不會受到傷害.
Since java 5 we have autoboxing, and the conversion between primitive and wrapper class is done automatically. Beware, however, as this can introduce subtle bugs and performance problems; being explicit about conversions never hurts.
這篇關于Java中的整數和int有什么區別?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!