我正在尝试将未知长度的动态数组拆分为多个部分,并将所有部分作为数组列表返回,列表中的每个数组都具有给定的长度。我在这里搜索了一个解决方案,但只遇到了固定长度数组的解决方案。我对此很感兴趣并想出了这个:
private static ArrayList<String[]> list = new ArrayList<String[]>();
public static ArrayList<String[]> split(String input[], int splitSize){
int place = 0;
int place2 = splitSize;
for(int i = 0; i < input.length/splitSize; i++){
String[] part = new String[splitSize];
System.arraycopy(input, place, part, place2, splitSize);
place = place + splitSize;
place2 = place2 + splitSize;
System.arraycopy(input, place, part, place2, splitSize);
list.add(part);
}
return list;
}
我不断遇到越界错误,但我不确定哪里错了。任何帮助将不胜感激,谢谢!
编辑: 对于那些使用谷歌搜索并寻找快速答案的人,此方法会拆分您的标准数组并将剩余部分添加到末尾:
public static String[][] split(String[] input, int splitSize) {
int numOfSplits = (int)Math.ceil((double)input.length / splitSize);
String[][] output = new String[numOfSplits][];
for(int i = 0; i < numOfSplits; ++i) {
int start = i * splitSize;
int length = Math.min(input.length - start, splitSize);
String[] part = new String[length];
System.arraycopy(input, start, part, 0, length);
output[i] = part;
}
return output;
}
最佳答案
String[] leftover = null;
System.arraycopy(input, place, leftover, place2, splitSize);
如何在 null
数组中复制内容?
参见 javadoc ,
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
抛出:
NullPointerException - if either src or dest is null.
EDIT 因为 OP 更改了代码:
你的问题在这里,
int place2 = splitSize;
您正在为 place2
分配 splitSize
,然后创建一个新的字符串数组,例如,
String[] part = new String[splitSize];
然后,您尝试将 input
复制到索引 splitSize
中的 part
中。请记住,数组是零索引的。
例如,splitSize = 2
。然后 part
将是长度为 2
的字符串数组,索引为 0
和 1
。
然后在 System.arraycopy(input, place, part, place2, splitSize);
行中,您正在尝试复制 part
的 2
索引。因此 ArrayIndexOutOfBoundsException
发生了。
这可能对您有帮助:
import java.util.ArrayList;
public class SplitArray {
private static ArrayList<String> list = new ArrayList<String>();
public static ArrayList<String> split(String input, int splitSize) {
int place = 0;
for (int i = 0; i < input.length() / splitSize; i++) {
String part = input.substring(place, place + splitSize);
list.add(part);
place += splitSize;
}
return list;
}
public static void main(String[] args) {
String input = "aabbcc";
split(input, 2);
}
}
关于java - 将动态数组拆分为多个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30950998/