Instantiating List<T> with generic type possible?

dtg picture dtg · Feb 27, 2013 · Viewed 7.1k times · Source

A student that I am tutoring is taking a web development class that uses a Dietel book on Java, which contains this curious bit of code involving Generics:

class StackComposition <T>
{
    private List<T> stackList;

    public StackComposition()
    {
        stackList = new List<T>("stack")  // ERROR
    }

    // .... more code
}

It is apparent to me why this code doesn't work, and I am puzzled as to why the instructor recommends the student use this code as a starting point. Maybe I am just not understanding Generics and my Java skills are deficient, but I don't see how one could instantiate a generic collection with a generic type. I see the intent is to create a Stack by using a generic List collection and determining the type at runtime, but I don't see how this is possible using the above configuration. My first inclination was to tell the student to use the Generic Stack<T> object and forget writing this custom Stack class, but apparently that isn't the goal of the assignment.

I tried as a test using the java.lang.reflect package to work around this, but as far as I can tell this only works with non-generic containers, such as Array:

public StackComposition(Class<T> type)
{
    Object obj = Array.newInstance(type, 10);
}

Answer

user2030471 picture user2030471 · Feb 27, 2013

There are two problems in your code:

You're trying to instantiate an interface with new keyword which is illegal. You should be instantiating an object of ArrayList (or a class which implements List) instead.

Second, you're not allowed to pass a String reference to the constructor.

So, here is what you should be using in your code:

stackList = new ArrayList<T>();

or stackList = new ArrayList<T>(10); if you want to give an initial size to your stackList (replace 10 with the size you want your list to be initialized with).