JAVA怎么把string数组转数组

在 Java 中将字符串数组转换为数组的方法是:1. 使用 Arrays.asList() 将字符串数组转换为 List。2. 使用 toArray() 方法将 List 转换为数组。(注意:转换后的数组类型为 Object[],需强制类型转换)

如何将 Java 字符串数组转换为数组

要在 Java 中将字符串数组转换为数组,可以使用 Arrays.asList() 方法将字符串数组转换为一个 List,然后使用 toArray() 方法将其转换为数组。需要注意的是,使用此方法转换的数组类型为 Object[],需要进行强制类型转换才能得到原始类型数组。

详细步骤:

  1. 首先,将字符串数组转换为 List:

    List stringList = Arrays.asList(stringArray);
  2. 接下来,使用 toArray() 方法将 List 转换为数组:

    // 将 List 转换为 Object[] 数组
    Object[] objectArray = stringList.toArray();
    
    // 强制类型转换 Object[] 数组为原始类型数组
    // 其中 T 为希望转换成的原始类型,例如 int[]、double[] 等
    T[] resultArray = (T[]) Array.newInstance(T.class, objectArray.length);
    System.arraycopy(objectArray, 0, resultArray, 0, objectArray.length);

示例:

public class StringArrayToArrayDemo {

    public static void main(String[] args) {
        // 定义一个字符串数组
        String[] stringArray = {"1", "2", "3", "4", "5"};

        // 将字符串数组转换为 int[] 数组
        int[] intArray = (int[]) convertStringArrayToIntArray(stringArray);

        // 输出转换后的 int[] 数组
        for (int value : intArray) {
            System.out.println(value);
        }
    }

    public static Object[] convertStringArrayToIntArray(String[] stringArray) {
        List stringList = Arrays.asList(stringArray);
        Object[] objectArray = stringList.toArray();
        int[] resultArray = new int[objectArray.length];
        for (int i = 0; i < objectArray.length; i++) {
            resultArray[i] = Integer.parseInt(objectArray[i].toString());
        }
        return resultArray;
    }
}

输出结果:

1
2
3
4
5