the mission is to convert a 2-dimensional array into a simple array and I try to copy the element of original array to the new array via for loop,for example
public static void main(String[] args) {
int[][] a = new int[5][8];
//initialize the 2-dimensional array with random number range(1~100)
assignNestedArray(a);
printNestedArray(a);
int[] arr=new int[a.length*a[0].length];
for(int i=0,k=0;i<a.length;++i,k+=a[i].length){
System.arraycopy(a[i], 0, arr, k, a[i].length);
}
System.out.println(Arrays.toString(arr));
}
public static void printNestedArray(int[][] a){
for (int[] sub_arr : a) {
for (int v : sub_arr)
System.out.print(v+" ");
System.out.println();
}
}
public static void assignNestedArray(int[][] a){
for (int i = 0; i < a.length; ++i)
for (int j = 0; j < a[i].length; ++j)
a[i][j] = (int) (Math.random() * 100);
}
which shows an Array index out of bounds exception
on the other hand, if I modify the array copy code like this:
for(int i=0,k=0;i<a.length;++i){
System.arraycopy(a[i], 0, arr, k, a[i].length);
k+=a[i].length;
}
It works well, I wonder what is the difference between those two codes and how to write a for loop with 2 elements update each time. Any advice is appreciate, thank you.