java 拆分数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/696113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
splitting arrays
提问by efe
How do I partition an array into four sub arrays in Java?
如何在 Java 中将数组划分为四个子数组?
回答by Markus Lausberg
Create 2 Array of the length you want to have it.
创建 2 个你想要的长度的数组。
And use
并使用
System.arraycopy(src, srcPos, dest, destPos, length)
to copy the values from the original to the two new target arraies.
将原始值复制到两个新的目标数组。
Example:
例子:
int[] original = new int [13];
int[] a = new int[3];
int[] b = new int[10];
System.arraycopy(original, 0, a, 0, 3);
System.arraycopy(original, 3, b, 0, 10);
回答by Zyx
Ordinary partitioning... I would use one of the two ways below:
普通分区...我会使用以下两种方法之一:
If you need to move groups of items into separate arrays, for example items 0 to 10 to array 1, 11 to 20 to array 2 etc., I would create four arrays and use
System.arraycopy()static method:System.arraycopy(sourceArray, sourceStart, destArray, destStart, length);If you must check, where a particular item should go, create four arrays, four index counter variables and make a loop through the elements of the original array. Test the condition and add it to one of the four arrays, incrementing the appropriate index counter.
如果您需要将项目组移动到单独的数组中,例如项目 0 到 10 到数组 1、11 到 20 到数组 2 等,我将创建四个数组并使用
System.arraycopy()静态方法:System.arraycopy(sourceArray, sourceStart, destArray, destStart, length);如果您必须检查特定项目应该放在哪里,请创建四个数组、四个索引计数器变量并循环遍历原始数组的元素。测试条件并将其添加到四个数组之一,增加适当的索引计数器。
回答by Tobias Müller
In addition to what was already said, you could use one of the Arrays.copyOfRange(...)methods available in class java.util.Arrays.
除了已经说过的内容之外,您还可以使用class 中可用的Arrays.copyOfRange(...)方法之一java.util.Arrays。
回答by diggi
See my answer here:
在这里看到我的回答:
Split an array in multiple arrays with a specific maximum size
What's the maximum size you have to evaluate by dividing the array length by the number of sub arryas (beware of float results, it must be an Integer).
您必须通过将数组长度除以子 arryas 的数量来评估的最大大小是多少(注意浮点结果,它必须是整数)。

