1

To create array of generic, I have seen below recommendation in many websites including this one, too. However, I wonder why we do not use directly the generic class in array creation. What is the reason to push us to not use below array creation method?

What currently is used

public class X<T>  {

    private Y<T> tTypeClass = null;

    public T[] Array() {       
        T[] array = (T[]) Array.newInstance(tTypeClass.getObject().getClass(),4); 
    }
}

Why we do not use

public class X<T>  {

    public T[] arrayCreation() {       
        T[] array = (T[]) Array.newInstance(this.getClass(),4); 
    }
}

2 Answers 2

1

You can't write code like T[] arr = new T[xx] because Java generics are type-erased. The Runtime has no idea what T is during runtime, because the Java compiler replaced all generics with casts at compile time.

Also,

public class X<T>  {

    public T[] arrayCreation() {       
        T[] array = (T[]) Array.newInstance(this.getClass(),4); 
    }
}

will cause a ClassCastException because it creates an array of X[] and tries to cast it to T[].

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

Comments

0

Because the cast is not safe. For example:

String[] s = new X<String>().arrayCreation();

will result in java.lang.ClassCastException.

Comments

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.