Array 如何将原始数据类型视为对象?

How does Array treat primitive data types as objects?

我对 Java 编程有点陌生。两三天前,我遇到了一个关于数组的问题,下面给出。

每个Java程序员都知道,Array是Object的集合,不管它包含原始数据类型还是Strings

所以我的问题是,如果数组是对象的集合,那么它如何处理原始数据类型转换为objects,因为在Java中,原始数据类型不同于对象(如字符串)。 考虑以下程序:-

   int[] Array = new int[3];
   Array[0] = 1;
   Array[1] = 2;
   Array[2] = 4;`
   for(int a=0;a<Array.length;a++) System.out.println(Array[a]);

我使用 new 关键字创建了数组或数组对象,然后是 datatype。当然,这对于数组是可行的。但是当我对变量做这样的事情时,它会失败。

int var1 = new int 3;

注意,再问一下,在Java数组中如何对待转换原始数据类型为对象,因为通常原始数据类型是不是对象。

谢谢!

在java中,有2类类型:原始类型和引用(即对象)

数组类型(无论是原始数组还是对象数组)始终是引用类型。例如,int[]Object 的子类型。您可以在 int[] 上调用 Object 中的任何方法。

然而,int[] 是基元数组,而不是对象。

JLS-10. Arrays 说(部分),

In the Java programming language, arrays are objects (§4.3.1), are dynamically created, and may be assigned to variables of type Object (§4.3.2). All methods of class Object may be invoked on an array.

...

All the components of an array have the same type, called the component type of the array. If the component type of an array is T, then the type of the array itself is written T[].

The value of an array component of type float is always an element of the float value set (§4.2.3); similarly, the value of an array component of type double is always an element of the double value set. It is not permitted for the value of an array component of type float to be an element of the float-extended-exponent value set that is not also an element of the float value set, nor for the value of an array component of type double to be an element of the double-extended-exponent value set that is not also an element of the double value set.

tl;dr 基元数组仍然是 Object,但它的组件类型仍然是基元类型。最后,虽然它不适用于您的问题,但当在需要 Object 的地方使用原始类型时,Java 确实有一个名为 Autoboxing 的功能,可以将原始类型转换为相应的包装器类型(反之亦然,即拆箱)。但是数组可以存储原始类型(不像 Collection(s) 只能存储 Object 个实例)。