简体   繁体   English

在数组中,元素存储的是图元还是对象?

[英]In an array, are the elements stored Primitives or Objects?

int[] array = new int[10];
for (int i = 0; i < array.length; i++) {
    array[i] = 0;
}

in this example, is the value 0 stored inside the array as a primitive or as an object? 在此示例中,值0是作为基元还是作为对象存储在数组中的?

Many thanks 非常感谢

In this case, the value is stored as a primitive. 在这种情况下,该值将存储为原语。 If you changed the type to a primitive's wrapper Integer , the value would go in as an "auto-boxed" Object then. 如果将类型更改为原始的包装器 Integer ,则该值将作为“自动装箱” Object进入。 For example, this code would autobox your values: 例如,此代码将自动装箱您的值:

Integer[] array = new Integer[10];
for (int i = 0; i < array.length; i++) {
    array[i] = 0;
}

In Java, there are both arrays of primitives, and arrays of objects. 在Java中,既有基本数组,又有对象数组。

int[] is an array of primitives, so 0 is stored as a primitive. int[]是基元数组,因此0被存储为基元。

The corresponding array of objects would be of type Integer[] . 对应的对象数组将为Integer[]类型。 Storing 0 in such an array would result in it being "auto-boxed" into an Integer object. 在这样的数组中存储0将导致其“自动装箱”到Integer对象中。

It is worth pointing out that Java containers (and any other generic classes) can only work with objects. 值得指出的是,Java容器(和任何其他通用类)只能与对象一起使用。 For example, it is impossible to construct a List of int , only a List of Integer . 例如,不可能构造一个int List ,而只能构造一个Integer List As I've explained above, this restriction does not apply to arrays. 如上文所述,此限制不适用于数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM