How to convert an object array to an integer array in Java?

Java 8Object Oriented ProgrammingProgramming

You can convert an object array to an integer array in one of the following ways −

  • By copying each element from integer array to object array −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      int intArray[] = new int[length];
      for(int i=0; i<length; i++){
         intArray[i] = (int) objArray[i];
      }
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the arrayCopy() method of the System class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      Integer intArray[] = new Integer[length];
      System.arraycopy(objArray, 0, intArray, 0, length);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the copyOf() method of the arrays class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      int length = objArray.length;
      Integer[] intArray = Arrays.copyOf(objArray, length, Integer[].class);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
  • Using the toArray() method of the List class −

Example

import java.util.Arrays;
public class ObjectArrayToStringArray {
   public static void main(String args[]){
      Object[] objArray = {21, 58, 69, 33, 65};
      Integer[] intArray = Arrays.asList(objArray).toArray(new Integer[0]);
      System.out.println("Contents of the integer array: "+Arrays.toString(intArray));
   }
}

Output

Contents of the integer array: [21, 58, 69, 33, 65]
raja
Published on 08-Jul-2019 17:19:16
Advertisements