例如,为什么你可以做:

int n = 9;

而不是:

Integer n = 9;

你可以这样做:

Integer.parseInt("1");

而不是:

int.parseInt("1");

当前回答

Int是表示整数的基本类型。而Integer是一个包装int的对象。Integer对象提供了更多的功能,例如转换为十六进制、字符串等。

你也可以在Integer中使用OOP概念。例如,您可以使用Integer作为泛型(即Collection<Integer>)。

其他回答

本文摘自《Java:完整参考,第九版》

Java uses primitive types (also called simple types), such as int or double, to hold the basic data types supported by the language. Primitive types, rather than objects, are used for these quantities for the sake of performance. Using objects for these values would add an unacceptable overhead to even the simplest of calculations. Thus, the primitive types are not part of the object hierarchy, and they do not inherit Object. Despite the performance benefit offered by the primitive types, there are times when you will need an object representation. For example, you can’t pass a primitive type by reference to a method. Also, many of the standard data structures implemented by Java operate on objects, which means that you can’t use these (object specific) data structures to store primitive types. To handle these (and other) situations, Java provides type wrappers, which are classes that encapsulate a primitive type within an object. Wrapper classes relate directly to Java’s autoboxing feature. The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.

Integer是包装器类/对象,int是基本类型。当您想在集合中存储int值时,这种差异发挥了巨大的作用,因为它们只接受对象作为值(直到jdk1.4)。JDK5之后,因为自动装箱,它是一个完全不同的故事。

Int是基本类型,不是对象。这意味着没有与之关联的方法。Integer是一个具有方法的对象(例如parseInt)。

在更新的java中,有自动装箱(和解装箱)的功能。这意味着编译器将在需要的地方插入Integer.valueOf(int)或integer.intValue()。这意味着它实际上是可以写的

Integer n = 9;

它被解释为

Integer n = Integer.valueOf(9);

Int是一个基本类型。int类型的变量存储要表示的整数的实际二进制值。int. parseint("1")没有意义,因为int不是一个类,因此没有任何方法。

Integer是一个类,与Java语言中的其他类没有什么不同。Integer类型的变量存储对Integer对象的引用,就像任何其他引用(对象)类型一样。Integer.parseInt("1")是从类Integer调用静态方法parseInt(注意,该方法实际返回int而不是Integer)。

更具体地说,Integer是一个具有单个int类型字段的类。该类用于需要像对待任何其他对象一样对待int的地方,例如泛型类型或需要可空性的情况。

注意,Java中的每个基本类型都有一个等效的包装器类:

字节有字节 短有短 int有整数 长有长 布尔有布尔 char有字符 浮动有浮动 double有double

包装器类继承自Object类,而原语类则不是。所以它可以在集合中使用对象引用或泛型。

从java 5开始,我们就有了自动装箱,并且基本元素和包装类之间的转换是自动完成的。但是要注意,这可能会引入微妙的bug和性能问题;明确转换永远不会有坏处。

Int是表示整数的基本类型。而Integer是一个包装int的对象。Integer对象提供了更多的功能,例如转换为十六进制、字符串等。

你也可以在Integer中使用OOP概念。例如,您可以使用Integer作为泛型(即Collection<Integer>)。