Converting an int [] array to a short [] array in Java

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

Do I need to allocate new memory for inShort[] or is there a way I can use inInt[] ?

 int inInt[] = new int[100]; short inShort[]; 
+4
source share
4 answers
 short inShort[] = new short[100]; for(int i = 0; i < 100; i++) { inShort[i] = (short)inInt[i]; } 

However, you are likely to overflow short if int is out of range of short (i.e. less than -32.768 or more than 32 767). Actually it is very easy to overflow short, since int ranges from -2,147,483,648 to 2,147,483,647.

+11
source

I think you should allocate memory for inShort [] before converting.

But you may not need to convert. if memory is critical in your application, or you do not want to free inInt [] after conversion.
Just use the inInt [] element in expressions with "(short) inInit [x]"

+1
source

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

You need to create an array of shorts of the appropriate size and copy the contents. Although there are utility methods for copying arrays, I don’t know that it will copy an array of primitives and simultaneously convert values. Thus, you will most likely need to copy an element with an explicit for loop.

Do I need to allocate new memory for inShort [] ....

Yes. A new array is required ... if you do not have an existing array of the desired type and size, ready for reuse.

or is there a way I can use inInt []?

Not. You cannot convert an array-primitive type to another array-primitive type. The Java language will not allow this.


(And for the record, this applies to every array of primitives such as Java.)

+1
source

This can lead to loss of information, since the int type uses more memory than the short one. So, as Lirik said, you can use his method until you lose information. To do this, you need to make sure that the integer you are converting is in the range of the short type.

0
source

Source: https://habr.com/ru/post/1402809/


All Articles