3

I want to create an array of classes and I have these:

1)works fine

Class<MyClass>[] array = (Class<MyClass>[]) new Class<?>[list.size()];

2)java.lang.ClassCastException

Class<MyClass>[] array = (Class<MyClass>[]) Array.newInstance(MyClass.class, list.size());

3)we have a generic method , works fine

public static <T> List<T> method(T arg , T[] array){
    array = (T[]) Array.newInstance(arg.getClass(), 1);
    ArrayList<T> list = new ArrayList<T>(Arrays.asList(array));
    array[0] = arg;
    return new ArrayList<T>(Arrays.asList(array));
}

Please explain why we get the exception in 2 ? As I understand we are doing the same thing in 3 , so what's the difference ?

UPDATE

I guess my confusion is because we have:

Type mismatch: cannot convert from List< Class < MyClass > > to List< MyClass >

List<MyClass> list = Utils.addToList(MyClass.class, null);

Works

List<Class<MyClass>> list = Utils.method(MyClass.class, null);

I think I'm missing something , but I'm not sure what...

So it's finally clear what exacly I had in mind:

List<Class<MyClass>> list = Utils.method(MyClass.class, null);

Class<MyClass>[] array2 = (Class<MyClass>[]) Array.newInstance(MyClass.class.getClass(), list.size());

List<Class<MyClass>> list2 = Utils.method(MyClass.class, list.toArray(array2));

1 Answer 1

4

Both snippets 2 and 3 are creating a MyClass[], not a Class<MyClass>[].

The element type is determined by the first argument to Array.newInstance. If you want an array where each element is a Class reference, you need to pass in Class.class.

Note that generics and arrays don't play terribly nicely together - which is why you get a warning even for your "works fine" code.

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

5 Comments

... and I would guess it's more likely the OP wants MyClass[].
@Duncan: It's very unclear what the OP is really trying to do, to be honest. I'm just explaining their current code, and hoping that's enough to help...
I think , I understand what you mean , but I'm still confused . I updates my question , could you look?
@KatrinnaL: Well that's because you're passing a Class<MyClass> reference as the value of arg, so T is inferred to be Class<MyClass>, and you end up with a List<MyClass>. It's still very unclear what you're really trying to achieve.
Thanks, it helped me a lot to understand what I wanted to do :)

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.