It is supposed to be impossible to create an array of type T<U>. There should be more details in the Java Tutorials: try here and here. It has to do with type erasure, that it might be possible to add the wrong type if that were permitted.
You would appear to be returning an Object, because generic types are erased at run‑time. You cannot assign an Object to a String reference. You can try casting it to (String), but by using an explicit cast, you are abandoning the type‑safety provided by generics.
You're creating an Object. You can't make it any other type of array just by casting it - it's still an Object. So when you then try and assign it to a String it's not going to work regardless of what T is.
Joel Bijapurkar wrote:I also tried initializing the generic list as follows:
This compiled fine. But on execution the insertValue() function threw java.lang.ArrayStoreException
Because, as with your cast Object, the array is the wrong type. What you need is a T, and you can only do that by supplying T.class (or indeed a T array, as with Collection.toArray(T)).
However, you're much more on the right lines using Array.newInstance(), because that will return an array that IS useable as a T. You just need to get the class right.
One possiblilty to consider might be a static factory method, viz:
public static final <T> MyGeneric<T> newInstance(Class<T> elementClass, int length);
but, as Matthew said, you're probably far better off just using generic collections or Lists internally.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
She said she got a brazillian. I think owning people is wrong. That is how I learned ... tiny ad: