Java中的Integer和int有什么区别? [英] What is the difference between Integer and int in Java?
问题描述
例如你为什么可以这样做:
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
类型的变量存储对 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中的Integer和int有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!