Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an int array with object array return type

Tags:

java

casting

I am doing something like this :

public Object [] getApple() {
    return new int[4];
}

But Java compiler does not allow this. It says cannot convert from int[] to Object[].

While If I do something like this :

public Object  getApple() {
    return new int[4];
}

It compiles fine. Can anyone explains why int [] cannot be cast to Object [] implicitly?

like image 700
Upendra Sharma Avatar asked Mar 24 '26 09:03

Upendra Sharma


2 Answers

ints are not Objects, that is why. They are primitive data types, they play a special role and are not in the class tree with the all-parent Object.

The second example works because the int[] array itself can be interpreted as Object.


You can use the wrapper class Integer though, which is a subclass of Object:

public Object[] getApple() {
    return new Integer[4];
}

You can work with it similar to an int[] due to auto-boxing. So if you do

Integer[] values = (Integer[]) getApple();
values[1] = 5;

Java will automatically box the 5 into the corresponding Integer object that represents 5 and then add this Integer to the array.

Same happens if you do

int val = values[2];

Java will unbox the value from the Integer object and give you an int since val is of type int.

Note that auto-boxing does not work for arrays, so Java won't automatically convert your int[] into an Integer[]. It only works for int to Integer and vice versa (analogously for the other primitives like double etc).

like image 165
Zabuzard Avatar answered Mar 26 '26 00:03

Zabuzard


That is because array is an Object in Java. Hence when you try to return an int array as an Object, it was accepted.

However, when you tries to return an int array as array of Object it will be rejected because you are returning int array (an object) when the method return type is expecting (array of object).

public Object[] getApple()    //expecting (array of object) 
{  
    return new int[4];        //returning array (an object) Type mismatch!
}

If you run the following, it will be compilable:

public Object[] getApple()    //expecting (array of object) 
{  
    return new int[4][4];     //returning array of array (array of object) O.K!
}
like image 27
user3437460 Avatar answered Mar 25 '26 22:03

user3437460



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!