这里我有整数数组包含81
值,因此我需要为每个数组存储9
个值,我需要获得9个数组。例如:来自array1
的{{1}}和来自1 to 9
的{{1}}以及来自array2
的{{1}}。任何人都可以帮助我如何获得这些价值观吗?
10 to 18
如何获得理想的结果?
答案 0 :(得分:0)
您可以使用System#arraycopy()
:
int[] first_part = new int[27];
int[] second_part = new int[27];
int[] third_part = new int[27];
System.arraycopy(input, 0, first_part, 0, 27);
System.arraycopy(input, 27, second_part, 0, 27);
...
我刚刚注意到您需要9个部分,您可以轻松地将其放入循环并使用arraycopy
。
答案 1 :(得分:0)
public static void main(String[] args) {
int num = 85;
int limit = 5;
int index = 0;
int extra = 0;
int finalArrayIndex = 0;
int[] innerArray = null;
int[] input = new int[num];
boolean isEnd = false;
if (num % limit > 0) {
extra = 1;
}
int[][] finalArray = new int[(num / limit) + extra][limit];
for (int i = 0; i < input.length; i = i + (limit)) {
innerArray = new int[limit];
for (int j = 0; j < limit; j++) {
innerArray[j] = input[index++];
if (index >= input.length) {
isEnd = true;
break;
}
}
finalArray[finalArrayIndex++] = innerArray;
if (isEnd) {
break;
}
}
// just for test
for (int k = 0; k < finalArray.length; k++) {
for (int l = 0; l < finalArray[k].length; l++) {
System.out.println("finalArray[" + k + "]" + "[" + l + "] : "
+ finalArray[k][l]);
}
}
}
这是动态解决方案,您可以更改num
和limit
变量的值。我希望这会对你有所帮助:)
Java小提琴链接:http://ideone.com/jI8IOb
答案 2 :(得分:0)
我的建议是使用subList
您可以按照以下步骤操作。
List
(ArrayList
)List
subList()
您可以将List
转换为array
。
List<Integer> fullList=new ArrayList<>();
List<Integer> list1=fullList.subList(0,8); // first 9 elements
Integer[] bar = list1.toArray(new Integer[list1.size()]);