简体   繁体   中英

Check if array is single or multidimensional

I'm writing a class for my class that I'm going to be using as a helper class. However, I don't know if it's possible or not to check if any given array is single or multidimensional. What I currently have:

public class Grid {
    private Object[] board;

    public Grid( Object[] b ) {
        this.board = b;
    }
    public Grid( Object[][] b ) {
        this.board = b;
    }
}

but obviously that wouldn't work for any given array. Would I have to just make separate methods for the type of array? (Keep in mind we won't be using more than two-dimension arrays (at least yet)

Would it be best if I did this? (for example):

public Object getValue( Object[] b, int index ) throws ArrayIndexOutOfBoundsException {
    if ( index >= b.length ) {
        throw new ArrayIndexOutOfBoundsException( "Index too high" );
    }
    return b[ index ];
}

public Object getValue( Object[][] b, int index1, int index2 ) throws ArrayIndexOutOfBoundsException {
    if ( index1 >= b.length ) {
        throw new ArrayIndexOutOfBoundsException( "Index1 too high" );
    } else if ( index2 >= b[ 0 ].length ) {
        throw new ArrayIndexOutOfBoundsException( "Index2 too high" );
    }
    return b[ index1 ][ index2 ];
}

So, in essence, I'm wondering if it's possible to make the above example easier by simply being able to check if an array is multidimensional or not, and use that as a basis of my methods.

A multidimensional array is simply an array where each of the items are arrays. You can check if an array has sub-arrays in it by:

if (b.getClass().getComponentType().isArray()) {
    ...
}

Then you can do it recursively.

public void check(Object[] b, int... indices) {
    if (b.getClass().getComponentType().isArray()) {
        //check sub-arrays
        int[] i2 = Arrays.copyOfRange(indices, 1, indices.length);
        check(b[0], i2);
    }
    if (indices[0] > b.length) 
        throw new ArrayIndexOutOfBoundsException("Out of Bounds");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM