您可以通过以下方式之一将对象数组转换为整数数组:
通过将每个元素从整数数组复制到对象数组-
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)); } }
输出结果
Contents of the integer array: [21, 58, 69, 33, 65]
使用System类的arrayCopy()方法-
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)); } }
输出结果
Contents of the integer array: [21, 58, 69, 33, 65]
使用arrays类的copyOf()方法-
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)); } }
输出结果
Contents of the integer array: [21, 58, 69, 33, 65]
使用List类的toArray()方法-
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)); } }
输出结果
Contents of the integer array: [21, 58, 69, 33, 65]