Generic and cast in java Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Generic and cast in java without wasting too much if your time.

The question is published on by Tutorial Guruji team.

suppose i have the following code

E[] arrayVar = (E[])new Object[1];// It causes a compiler warning 

the question is, in what situation when the code will cause a run time error,

Answer

That code will only cause a runtime error if you try to assign the result to the reified type of E:

createArray(); // no exception
String[] arr = createArray(); // causes ClassCastException

public static <E> E[] createArray() {
    return (E[]) new Object[1];
}

The safe way to create generic arrays is with the use of Array.newInstance:

public static <E> E[] createArray(Class<E> component) {
    return (E[]) Array.newInstance(component, 1);
}

This method will not cause a ClassCastException.

We are here to answer your question about Generic and cast in java - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji