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.H开发者_如何学Goowever, 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 ?
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);
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.
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.
精彩评论