Convert int[] to Integer[] in Java - Java @ Desk

Tuesday, March 11, 2014

Convert int[] to Integer[] in Java




Convert int[] to Integer[] in Java


Following example will show you how to convert primitive "int" Array into Wrapper "Integer" Array


The example will start with int array convert that to Integer and then back to int array


package test;

public class IntArrToIntegerArr {

 public static void main(String[] args) {

  int[] educationLoanPrimitive = new int[] { 50000, 80000, 100000 };
  Integer[] educationLoanWrapper = convertIntArrToIntegerArr(educationLoanPrimitive);

  System.out.println("Primitive Array To Wrapper");
  for (Integer educationLoan : educationLoanWrapper) {
   System.out.println(educationLoan);
  }

  educationLoanPrimitive = convertIntegerArrToIntArr(educationLoanWrapper);

  System.out.println("Wrapper To Primitive Array");
  for (int educationLoan : educationLoanPrimitive) {
   System.out.println(educationLoan);
  }

 }

 public static Integer[] convertIntArrToIntegerArr(int[] educationLoan) {
  Integer[] educationLoanWrapper = new Integer[educationLoan.length];
  for (int i = 0; i < educationLoan.length; i++) {
   educationLoanWrapper[i] = Integer.valueOf(educationLoan[i]);
  }
  return educationLoanWrapper;
 }

 public static int[] convertIntegerArrToIntArr(Integer[] educationLoanWrapper) {

  int[] educationLoanPrimitive = new int[educationLoanWrapper.length];
  for (int i = 0; i < educationLoanWrapper.length; i++) {
   educationLoanPrimitive[i] = educationLoanWrapper[i].intValue();
  }
  return educationLoanPrimitive;
 }
}






No comments:

Post a Comment