I am trying to create a method in Java that reverses an array or matrix. The method's code as it is now looks like this:
@SuppressWarnings("unchecked")
public static <T> T[] reverse(T[] array) {
T[] ret = Array.newInstance(array.getClass().getComponentType(), array.length);
for(int i = 0; i < array.length; i++) {
if (array[i].getClass().getComponentType() != null) {
ret[array.length - 1 - i] = (T) reverse((T[]) array[i]); // the exception (see below) occurs here
} else {
ret[array.length - 1 - i] = array[i];
}
}
return ret;
}
When I tried to run this method with a 2-dimensional String matrix, it worked out well. Now I tried to use an 2-dimensional int matrix instead and I get the following exception:
Exception in thread "main" java.lang.ClassCastException: [I cannot be cast to [Ljava.lang.Object;
How come this code works with String arrays, but not with int arrays? How can I fix the code to work with int arrays as well?
@EDIT I just noticed that I asked this question wrong. *facepalms* What I originally wanted to know is: how do I check if array[i] is an array or not?