Creating Generic Arrays in Java

In project 1 you'll need to create a generic array, but doing so in Java can be a bit awkward at first. Let's say we have the following class:

  public class MyGenericClass<E>
    private E value;
    void assign(E val){value=val;}
    E get(){return value;}
It allows assignment and retrieval of an object of some generic type E. So far so good.

Now let's say we wanted to store more than one object of type E; we should just be able to do something like the following, right?

  E[] myGenericArray=new E[128];

But if we try that, Java gives us the following compilation error: Cannot create a generic array of E

To get around this, you can create an Object array and cast it, like this:

  E[] myGenericArray=(E[])new Object[128];

You should then be able to use the generic array just as you'd expect.