Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 890
Kirill Avatar asked Aug 28 '17 11:08

Kirill


People also ask

Do arrays autobox?

Arrays are never autoboxes or auto-unboxed, e.g. if you have an array of integers int[] x , and try to put its address into a variable of type Integer[] , the compiler will not allow your program to compile.

What is the major advantage of Autoboxing?

Autoboxing and unboxing lets developers write cleaner code, making it easier to read. The technique lets us use primitive types and Wrapper class objects interchangeably and we do not need to perform any typecasting explicitly.

What is the difference between boxing and Autoboxing?

Boxing is the mechanism (ie, from int to Integer ); autoboxing is the feature of the compiler by which it generates boxing code for you. For instance, if you write in code: // list is a List<Integer> list.

What happens in Autoboxing?

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.


1 Answers

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];
like image 75
Naman Avatar answered Sep 25 '22 13:09

Naman