Java 中将对象转换为数组有两种方法:一是使用 Collections.toArray() 方法将集合转换为数组;二是使用反射动态创建数组并填充元素值。
Java 中将对象转换为数组的两种方法
问题:如何将 Java 中的对象转换为数组?
方法 1:使用 Collections.toArray() 方法
T[] toArray(T[] a),其中 T 是数组中元素的类型,a 是要填充其内容的数组。示例:
Listnumbers = List.of(1, 2, 3 , 4, 5); Integer[] array = numbers.toArray(new Integer[numbers.size()]);
方法 2:使用反射
示例:
Classtype = Integer.class; int[] array = (int[]) Array.newInstance(type, 5); array[0] = 1; array[1] = 2;