I have a method, that accepts int[] parameter. I want to pass it an array of shorts. But all I get is "incompatible types: short[] cannot be converted to int[]". Why is that? an example:
short[] arr = new short[2];
arr[0] = 8;
arr[1]=9;
example(arr);
example(int[] anArray){
}
As far as I know, short to int is just widening, so it should be typecasted automatically, shouldn't it? How to pass it then? Thanks.
Yes, a short will be automatically promoted to an int.
When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference). Therefore, any changes to this array in the method will affect the array.
Arrays can be passed to other methods just like how you pass primitive data type's arguments. To pass an array as an argument to a method, you just have to pass the name of the array without square brackets. The method prototype should match to accept the argument of the array type.
for(x = 0; x < 4; ++x) num[x] = 100; Unicode value \u0000 is also known as null. When you pass an array element to a method, the method receives a copy of the value in the element.
You can't do that, because a short[]
is not an int[]
. Also, a short
is not an int
, it's just that Java allows a primitive widening conversion to allow a short
to be widened to an int
. However, there is no such primitive widening conversion for arrays of primitive types.
That forces a few core Java APIs to accept many different types of primitive arrays, such as Arrays.sort
, which has overloads for many different types of primitive arrays.
If you'd like to do the same thing to a short[]
that you've already done to an int[]
, you must provide an overloaded method, such as example(short[] anArray)
.
The JLS, Section 5.1, specifies all types of conversions, and specifically disallows those not listed in 5.1.12, "Forbidden Conversions":
> Any conversion that is not explicitly allowed is forbidden.
Conversions between types of primitive arrays are not listed, so they're not allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With