当您在 java 中声明 Integer i = 9 时,由于自动装箱, i 是否被视为原始类型?

When you declare Integer i = 9 in java, is i considered to be primitive type due to autoboxing?

在类中声明时:

Integer i = 9;

我相信由于自动装箱,它现在符合要求,i 是否被视为原始数据类型?

是的,它是自动装箱的,所以 i 将指向一个值为 9 的 Integer 对象,而不是原始类型。

不,i 的类型仍然是 Integer(引用类型)——毕竟它是这样声明的。它恰好使用 int 初始化的事实与变量的类型完全不同。文字 9 是类型 int 的值,但它被装箱到 Integer.

代码等同于:

Integer i = Integer.valueOf(9);

不,它是一个(对一个)对象实例。由于自动装箱,原始文字 9 被转换为 Integer 实例并由 i.

引用

请参阅 Java 语言规范 (JLS) 的 5.1.7. Boxing Conversion

Boxing conversion converts expressions of primitive type to corresponding expressions of reference type... At run time, boxing conversion proceeds as follows:

If p is a value of type int, then boxing conversion converts p into a reference r of class and type Integer, such that r.intValue() == p

为了证明 i 不是原始变量,只需将 null 赋值给它,这对于原始变量是不可能的。

不,i 的类型 不是 被认为是原始类型:它是 java.lang.Integer,一种包装类型,由编译器自动装箱。

使它看起来像基元的部分原因是 Java 实习小整数,因此您可以将它们作为基元进行比较:

Integer a = 9;
Integer b = 9;
if (a == b) { // This evaluates to true
    ...
}

通常,与 == 的值相等比较是为基本类型保留的;您应该使用 a.equals(b) 作为参考对象。但是,上面的表达式的计算结果也为 true,因为 Java 保留了小型 Integer 包装器的内部缓存。

Integer is a wrapper class for the primitive type int, but with some little other features/methods, such as converting the same integer to a string. From the documentation 你有:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int. In addition, this class provides several methods for converting an int to a String and a String to an int, as well as other constants and methods useful when dealing with an int.

这里有Javawrapper classes的描述。