Home > Software engineering >  Java is there a way to get the size of an array without knowing the type?
Java is there a way to get the size of an array without knowing the type?

Time:12-25

My Object param can either be an int[] array or an Integer[] array. Is there a way to determine the size without having to manually check if its a int[] or Integer[] type?

int length = ((Object[]) param).length does not work for int[] (it causes a ClassCastException)

My current approach is to use:

int length = param instanceof int[] ? ((int[]) param).length : ((Integer[]) param).length;

I wonder if there might be a way to cast param that works in both cases, so I can avoid having to check manually every time.

edit: I accidentally used both "x" and "param" to name my variable. Now Im only using "param" to make the question less confusing.

CodePudding user response:

Yes. Use Array.getLength()

Object x; // assuming it’s an array
int length = Array.getLength(x);

CodePudding user response:

Because int is a primitive and Integer is an object, there really should be no reason that I can think of that you should be in this situation in the first place.

Anyway, you can just do param.length without the cast - the length of the array does not dependent on it's type.

  • Related