如何在 Java 中将对象数组转换为整数数组?
可以通过以下任一方法将对象数组转换为整数数组 −
- 通过将每个元素从整数数组复制到对象数组 −
示例
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]
- 使用数组类的 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]
广告