开发者

java convert object array to int array

how i can do this? i have an object array id like to convert it to int ar开发者_如何学编程ray


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;


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.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜