Home ArrayStoreException while trying to copy array in java
Reply: 1

ArrayStoreException while trying to copy array in java

Mirac B.
1#
Mirac B. Published in 2018-02-14 04:52:43Z

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;
}
user6690200
2#
user6690200 Reply to 2018-02-14 17:11:07Z

Reason

From the doc of Array.newInstance():

public static Object newInstance(Class<?> componentType,int... dimensions)
                      throws IllegalArgumentException,
                             NegativeArraySizeException

If componentType represents an array class, the number of dimensions of the new array is equal to the sum of dimensions.length and the number of dimensions of componentType

Since you create 2d array by:

Object[][] new_array = (Object[][]) Array.newInstance(a.getClass().getComponentType(),
        dim1_newLength, dim2_newLength);

Considering a is an array, new_array will have three dimensions, new_array[x] will have two dimensions, which will cause ArrayStoreException when running System.arrayCopy() because type mismatch.

Solution

create new 2d array with below and make sure a[0][0] not null

Object[][] new_array = (Object[][]) Array.newInstance(a[0][0].getClass(),
        dim1_newLength, dim2_newLength);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.319732 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO