Reputation: 6269
Integer extends Number so in that sense Number becomes the superclass of int. I want to store an int array into a Number array.. I have the following code.However, it seems it is not allowed in java.
int[] b = {1,2};
Number[] a = b;
Why java does not allow me to store an int array in number array and how do I store this out ?
Upvotes: 1
Views: 197
Reputation: 691635
Because int and Integer are two separate types. The first one is a primitive type, and the second one is an object type. Integer extends Number, but int is not even a class, and it thus can't extend anything.
Upvotes: 5
Reputation: 597016
You can't do that directly, because an "array-of-primitives" is not an "array-of-objects". Autoboxing does not occur with arrays.
But you can use ArrayUtils.toObject(b)
(from commons-lang). This will create a new array of the wrapper type (Integer
) and fill it with the values from the primitive array:
int[] a = {1,2};
Number[] n = ArrayUtils.toObject(a);
Upvotes: 5
Reputation: 6043
I would guess this has something to do with Number
being an abstract class (API Page), meaning the it cannot be used to represent an item, but allows other classes to share functionality. If you could store items in a Number
array, they would lose their type, and become instances of Number
, which is impossible as it's abstract.
Upvotes: -1