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

如何将 Java 字符串数组转换为数组
要在 Java 中将字符串数组转换为数组,可以使用 Arrays.asList() 方法将字符串数组转换为一个 List,然后使用 toArray() 方法将其转换为数组。需要注意的是,使用此方法转换的数组类型为 Object[],需要进行强制类型转换才能得到原始类型数组。
详细步骤:
首先,将字符串数组转换为 List:
立即学习“Java免费学习笔记(深入)”;
<code class="java">List<String> stringList = Arrays.asList(stringArray);</code>
接下来,使用 toArray() 方法将 List 转换为数组:
<code class="java">// 将 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);</code>
示例:
<code class="java">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<String> 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;
}
}</code>输出结果:
<code>1 2 3 4 5</code>
以上就是JAVA怎么把string数组转数组的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号