gpt4 book ai didi

java - 将数组分解为子数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:21:27 25 4
gpt4 key购买 nike

我有一个数组,例如:

{ "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12" }

我想把它分解成子数组。当我对其进行测试时,它显示错误:

java.lang.ArrayStoreException at line: String[] strarray = splitted.toArray(new String[0]);

代码:

public static String[] splittedArray(String[] srcArray) {
List<String[]> splitted = new ArrayList<String[]>();
int lengthToSplit = 3;
int arrayLength = srcArray.length;

for (int i = 0; i < arrayLength; i = i + lengthToSplit) {
String[] destArray = new String[lengthToSplit];
if (arrayLength < i + lengthToSplit) {
lengthToSplit = arrayLength - i;
}
System.arraycopy(srcArray, i, destArray, 0, lengthToSplit);
splitted.add(destArray);
}
String[] strarray = splitted.toArray(new String[0]);
return strarray;
}

最佳答案

来自 java.lang.ArrayStoreException documentation :

Thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects.

您正试图将 String[][] 存储到 String[] 中。修复只是在返回类型和传递给 toArray 方法的类型中。

String[][] strarray = splitted.toArray(new String[0][0]);

关于java - 将数组分解为子数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11878569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com