Kirill
Kirill

Reputation: 1610

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?

Upvotes: 10

Views: 1548

Answers (3)

Stephen C
Stephen C

Reputation: 718996

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

Boxing converts an instance of a primitive type to an instance of the corresponding wrapper type. However, this doesn't apply to array types; see Java: Array of primitive data types does not autobox.

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 design decision. However, a couple of the more obvious reasons are:

  • Efficiency. Converting an int[] to an Object[] entails visiting and converting all elements of the array. That is an expensive (O(N)) operation, 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.

Just rewrite your code like this:

Object[] arr = new Integer[3];

Upvotes: 8

Dhruvil Vaghela
Dhruvil Vaghela

Reputation: 590

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

Upvotes: 3

Naman
Naman

Reputation: 31938

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];

Upvotes: 8

Related Questions