Wednesday, April 3, 2013

Generic Array Creation

I was trying to create a new Generic Stack and noticed an issue.This might be a trivial one, but surprisingly, i never came across this issue. My Bad.

public class Stack<T> {
    private T[] array;
    int header;
    public Stack() {
       array = new T[25]; -- Compilation issue
       setHeader(-1);
    }

In the above mentioned step, during Compile time, Java doesn't know anything about T, so through erasure, it would be reduced to Object class. In which case, it would treat the statement as
T[] array = new Object[25] -- which is an error.

This link gives more information on why Generic Array Creation is a compilation issue



No comments: