简体   繁体   中英

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?

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. 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.

int[] is an array of primitives, so 0 is stored as a primitive.

The corresponding array of objects would be of type Integer[] . Storing 0 in such an array would result in it being "auto-boxed" into an Integer object.

It is worth pointing out that Java containers (and any other generic classes) can only work with objects. For example, it is impossible to construct a List of int , only a List of Integer . As I've explained above, this restriction does not apply to arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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