Java – Generic Array Creation

arraysgenericsjava

Here is the code I'm using

public class aClass<T> {

    private T[] elements;

    public aClass(T[] elements) {
        this.elements = elements;
    }

    public void doSomething() {
        T[] newArray = (T[]) new Object[5];
        ...
    }

}

I've seen people saying that creating an array like this is a bad idea, due to it being not type safe. However, every time I use it, I have no problems with it. When would creating an array like this cause a problem?

Thanks

Best Solution

Here is an example that causes issues:

public class Main {

    public static class List<E extends Number> {

        private E[] myE;

        public void hello(E e) {
            E[] newArray = (E[]) new Object[5];
            for (int i = 0; i < newArray.length; i++) {
                newArray[i] = e;
            }
            myE = newArray;
        }

    }

    public static <T> T[] createArray(int size) {
        return (T[]) new Object[size];
    }

    public static void main(String[] args) throws IOException {
        List<Integer> integers = new List<Integer>();
        integers.hello(5);
    }
}

Your code works because when you declare your generic parameter <T> it is unbound, meaning that it extends Object. When you cast your array to (T[])you are actually casting to (Object[]) because that is the best the compiler can do. Now, if you keep your array inside your code, you should not have too many problems. But if somebody outside your code can retrieve that array and has instantiated your class with a type other than object, he will have ClassCastException.