简体   繁体   English

java将对象数组转换为int数组

[英]java convert object array to int array

how i can do this? 我该怎么做? i have an object array id like to convert it to int array 我有一个对象数组ID,喜欢将其转换为int数组

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

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*/]; 如果您的objectArray类似于Object[] objectArray = new Integer[/*length*/];

You can simply cast (Integer []) objectArray; 您可以简单地转换(Integer []) objectArray;

If the content can be casted to Integer , you can cast the array to Integer [] and use its elements as int : 如果可以将内容转换为Integer ,则可以将数组转换为Integer []并将其元素用作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 []数组,然后将新创建的数组中的元素设置为转换给定的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM