I have a problem with changing the length of the 2d array in java. After allocating space for the 2d array I can't copy old array's values to the new array. But I can do it on 1d arrays with similar code. Here is the working code:
public static Object[] changeLength1D(Object [] a, int n, int new_length){
if(n > new_length){
throw new IllegalArgumentException("n must be greater or equal to new_length");
}
// Allocate space for 1d array
Object[] new_array = (Object[]) Array.newInstance(a.getClass().getComponentType(), new_length);
// Efficient array copy from a[0:n-1] to new_array
System.arraycopy(a, 0, new_array, 0, n);
return new_array;
}
But same logic is not working here. When I use arraycopy , java throws this:
Exception in thread "main" java.lang.ArrayStoreException
at java.base/java.lang.System.arraycopy(Native Method)
Here is the code for 2d array:
public static Object[][] changeLength2D(Object [][] a, int dim1_limit, int dim2_limit,int dim1_newLength, int dim2_newLength){
if(dim1_limit > dim1_newLength || dim2_limit > dim2_newLength){
throw new IllegalArgumentException("Limits must be <= new lengths");
}
// Allocate space for 2d array
Object[][] new_array = (Object[][]) Array.newInstance(a.getClass().getComponentType(),
dim1_newLength,dim2_newLength);
// Copy by rows
for(int x = 0; x < dim1_limit; x++){
System.arraycopy(a[x], 0, new_array[x], 0 ,dim2_limit); // EXCEPTION THROWS RIGHT THIS LINE
}
return new_array;
}