4

I have an int array for which i have allocated space for 100 elements. There is another array inShort[]. How can I convert inInt[] to inShort[]?

Is it necessary to allocate new memory for inShort[] or there is a way through which I can cast to inInt[]?

int inInt[] = new int[100];
short inShort[];
Mysticial
  • 464,885
  • 45
  • 335
  • 332
Rog Matthews
  • 3,147
  • 16
  • 37
  • 56
  • 2
    First, you will get a compiler warning as you're trying to save a bigger type into a smaller one. Second, yes, you have to create a new array of type short, so you can copy the values from one to the other. You can't retype an array as far as I know. – Eddie Paz Mar 22 '12 at 05:21

4 Answers4

12
short inShort[] = new short[100];

for(int i = 0; i < 100; i++)
{
    inShort[i] = (short)inInt[i];
}

However, you are very likely to overflow the short if the int is outside the range of the short (i.e. less than -32,768 or greater than 32,767). It's actually really easy to overflow the short, since an int ranges from -2,147,483,648 to 2,147,483,647.

Kiril
  • 39,672
  • 31
  • 167
  • 226
1

I think you must allocate memory for inShort[] before convert.
But you may not need to convert. if memory is critical in your application, or and you don't want to free inInt[] after convert.
Just use inInt[]'s element in expressions with “(short) inInit[x]”

zhu
  • 374
  • 1
  • 3
  • 10
1

How can I convert inInt[] to inShort[]?

You have to create an array of shorts of the appropriate size, and copy the contents. While there are utility methods for copying arrays, I'm not aware of any that will copy an array of primitives and convert values at the same time. So you most likely need to do the element copying with an explicit for loop.

Is it necessary to allocate new memory for inShort[] ....

Yes. A new array is required ... unless you have an existing array of the right type and size ready to re-use.

or there is a way through which I can cast to inInt[]?

No. You can't cast an array-of-primitive type to a different array-of-primitive type. The Java language won't allow it.


(And for the record, this applies to each and every Java array-of-primitive type.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

This can lead to loosing information as the int type use more memory as compared to short. So as said by Lirik you can use his method until you do not loose information. For that you have to make sure that the integer you are converting is in the range of short type.

me_digvijay
  • 5,374
  • 9
  • 46
  • 83