- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to convert an object array to an integer array in Java?
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]
Advertisements