Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I pass in java an array of short to method accepting array of int?

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.

like image 361
Leprechaun Avatar asked Mar 06 '14 17:03

Leprechaun


People also ask

Can you pass a short into a method call when an int is expected Java?

Yes, a short will be automatically promoted to an int.

When you pass an array to a method the method receives in Java?

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.

How do you pass an array to a method?

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.

When you pass an array element to a method the method receives?

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.


1 Answers

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.

like image 195
rgettman Avatar answered Oct 12 '22 23:10

rgettman