What is wrong with this piece of code?
public class HelloWorld {
public static void main(String[] args) {
int[] a={4,3,2,5,1,8,6,7};
System.out.println(Arrays.toString(HelloWorld.split_array(a)[0])); //expect 4325 here
}
public static int[][] split_array(int[] a){
int [][] result={};
int mid = (int) (a.length)/2;
result[0] = Arrays.copyOfRange(a, 0, mid);
result[1] = Arrays.copyOfRange(a, mid, a.length);
return result;
}
}
You have initialized
resultto be an empty array. Arrays in Java do not grow automatically like in scripting languages. Instead, you need to allocate them to the correct size. In this case, you need to do:This will create a new array of size 2 of int arrays, then you can assign the arrays as expected.