1

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?

1
  • because int is not an Object Commented Nov 27, 2014 at 9:45

1 Answer 1

4

Use Integer instead. int is a primitive type where String is an object type.

See Restrictions on Generics:

Cannot Instantiate Generic Types with Primitive Types

See also the example they provide:

Quote >

class Pair<K, V> {

    private K key;
    private V value;

    public Pair(K key, V value) {
        this.key = key;
        this.value = value;
    }

    // ...
}

When creating a Pair object, you cannot substitute a primitive type for the type parameter K or V:

Pair<int, char> p = new Pair<>(8, 'a');  // compile-time error

<

Sign up to request clarification or add additional context in comments.

2 Comments

I'm sorry, I asked this question wrong. Your answer is - of course - correct concerning my problems with String[] and int[], but I originally wanted to know how I can check if a variable is an array or not.
@flashdrive2049 if(someObj.getClass().isArray())? Or if(someObj instanceof Object[])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.