1

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 ?

3
  • 2
    beware Integer is the object, and int are a primitive type. Commented Oct 3, 2011 at 19:42
  • To do that make the int array into an Integer array: Integer[] b = {1,2}; then you can Number[] a = b; Commented Oct 3, 2011 at 19:50
  • "Integer extends Number " but int does not :) Commented Oct 3, 2011 at 19:50

3 Answers 3

5

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);
Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

-1

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.

2 Comments

An object never loses its type. If you store an Integer inside an array of Numbers, it stays an Integer. It's just referenced, in the array, as a Number. And it's alright, since an Integer is a Number. If I put you in a queue of travellers, to me, you're just a traveller. But that doesn't mean you lose your identity of ianhales.
Fair enough, my Java is rusty to say the least! This is what I get for working in Matlab these days ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.