Saturday 4 January 2020

How to convert float[] to Float[] in Java?


By traversing each element of array we can convert float[] to Float[].
public static Float[] getBoxedArray(float[] arr) {
 if (arr == null)
  return null;

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


App.java
package com.sample.app;

public class App {

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

 public static Float[] getBoxedArray(float[] arr) {
  if (arr == null)
   return null;

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

 public static void main(String args[]) {
  float[] arr = { 1.1f, 3.3f, 5.5f, 7.7f, 2, 4, 6, 8, 10 };

  Float[] result1 = getBoxedArray(arr);

  printElements(result1);

 }

}

Output
1.1 3.3 5.5 7.7 2.0 4.0 6.0 8.0 10.0


You may like

No comments:

Post a Comment