4

how i can do this? i have an object array id like to convert it to int array

1
  • what does the object array contain? Commented Dec 21, 2010 at 11:38

2 Answers 2

7

if Object[] objectArray like objectArray = {2,23,42,3} then

public static Integer[] convert(Object[] objectArray){
  Integer[] intArray = new Integer[objectArray.length];

  for(int i=0; i<objectArray.length; i++){
   intArray[i] = (Integer) objectArray[i];
  }

  return intArray;
 }

if your objectArray is like Object[] objectArray = new Integer[/*length*/];

You can simply cast (Integer []) objectArray;

1
  • +1 good one ! can be converted into int leveraging Autoboxing feature ! Commented Dec 21, 2010 at 12:15
0

If the content can be casted to Integer, you can cast the array to Integer [] and use its elements as int:

Object [] arr = new Integer[3];
arr[0] = new Integer(1);
arr[1] = new Integer(2);
arr[2] = 3;
Integer [] newa = (Integer []) arr;
for(int i:newa) {
  System.err.print(i+" "); 
}

Otherwise you can create a new int [] array with the same length as the original and then set the elements in the newly created arrays to the values given by conversion:

int [] arr = new int[origarr.length];
arr[0] = convertTo_int(origarr[0]);
// convertTo_int implementation depends on the type of origarr elements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.