简体   繁体   中英

Why autoboxing doesn't work in arrays?

I don't understand why this code is not compiling:

 Object[] arr = new int[3];

I don't need this code to work. I just want to understand the reason why autoboxing desn't work in this case?

From this answer to Why do we use autoboxing and unboxing in Java? , I would quote the relevant details for your question to be answered:

Primitive variables aren't interchangeable in the same way, neither with each other, nor with Object . The most obvious reason for this (but not the only reason) is their size difference. This makes primitive types inconvenient in this respect, but we still need them in the language (for reasons that mainly boil down to performance).

Hence on the other hand, what shall work for you is:

Object[] arr = new Integer[3];

Boxing converts an instance of a primitive type to an instance of the corresponding wrapper type.

It doesn't apply to array types.

Why?

  • Because that's how the language designers designed Java, and what the JLS specifies. The details are in JLS 5.1.7 .

The JLS authors did not include an explanation for this decision. However, there are a number of reasons. Here are couple of the more obvious ones.

  • Efficiency. Converting an int[] to an Object[] entails visiting and converting all elements of the array. That is expensive (O(N)) ... and not something that should be hidden from the programmer behind some syntax.

  • Boxing an array would necessarily create a new array that is inherently different to the original one. You would be able to tell this in the following:

     int[] ints = new int[]{1,2,3}; Integer[] arr = ints; // hypothetical boxing of the elements // What does ints.equals(arr) return? array[1] = 0; // What does ints[0] contain now? 

    By contrast, (real) boxing and unboxing converts between values that are only distinguishable if you compare pointers ... and even then, not reliably.

The bottom line is that extending boxing and unboxing would introduce both efficiency and conceptual problems that would be hard to resolve.

An array is an object in Java as per the JLS 4.3.1

So, one cannot assign int[] to Object[], or vice versa, as they're incompatible types.

Although, autoboxing does work for the elements of the array:

int[] a = new int[3];
a[0] = new Integer(0);
a[1] = 1;
a[2] = new Integer(2);

System.out.println(a[0]);
System.out.println(a[1]);
System.out.println(a[2]);

Output:

0
1
2

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