amirani amirani - 1 year ago 58
Java Question

Does all arrays in java implement same interface ?

I want to write method which will check array size and if its greater then SIZE I want to throw error, however i don't know dimensions of array.

For example:

private void checkValidSize(int[] arr){
if (arr.length > SIZE)
throw new RuntimeException(Messages.WRONG_INPUT_ERROR);


If I call it with 1d array it works fine but it doesn't works for 2d arrays.
As I understand 2d array is array itself containing arrays so i just need method which takes any kind of array as argument and measures its length.

If i knew that all arrays implement some kind of interface like IMesurable I would just wait for IMesurable in checkValidSize.

Is there anything like that or any other option so my function will work on any kind of array?

Answer Source

There are essentially 2 ways.

Way #1 is to use overloads. Arrays are covariant, so any array that's not a one dimensional primitive array is assignable to an Object[].

// this method accepts e.g.
// String[]
// int[][]
// etc...
static void checkValidSize(Object[] arr) {...}

// now define an overload for every primitive
static void checkValidSize(char[] arr) {...}
static void checkValidSize(int[] arr) {...}

Way #2 is to use java.lang.reflect.Array.

static void checkValidSize(Object shouldBeArr) {
    if (java.lang.reflect.Array.getLength(shouldBeArr)) {

The major downside to that is there is no compilation checking of what you pass to it. You can pass something to it that's not an array.

(Some people might say "reflection is slow!" but that depends entirely on what you're doing. getLength is specially recognized by HotSpot nowadays and it gets inlined.)