Saturday 4 January 2020

How to convert short[] to Short[] in Java?


By traversing to each element of short array, you can convert short[] to Short[].

public static Short[] getBoxedArray(short[] arr) {
 if (arr == null)
  return null;

 Short[] result = new Short[arr.length];
 int index = 0;
 for (short i : arr) {
  result[index] = Short.valueOf(i);
  index++;
 }
 return result;
}


App.java
package com.sample.app;

public class App {

 private static void printElements(Short[] arr) {
  for (short i : arr) {
   System.out.print(i + " ");
  }
  System.out.println();
 }

 public static Short[] getBoxedArray(short[] arr) {
  if (arr == null)
   return null;

  Short[] result = new Short[arr.length];
  int index = 0;
  for (short i : arr) {
   result[index] = Short.valueOf(i);
   index++;
  }
  return result;
 }

 public static void main(String args[]) {
  short[] arr = { 1, 3, 5, 7, 2, 4, 6, 8, 10 };

  Short[] result1 = getBoxedArray(arr);
  printElements(result1);

 }

}

Output
1 3 5 7 2 4 6 8 10


You may like

No comments:

Post a Comment