问题描述:

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.

相关阅读:
Top