Possible Duplicate:
Create instance of generic type in Java?
Java how to: Generic Array creation
I am trying to create a create a class of generic type. This is my class file.
public class TestClass<T> implements AbstractDataType<T>{
T[] contents;
public TestClass(int length) {
this.contents = (T[])new Object[length];
}
}
But the contents have just have the methods inherited from the Object class. How can I create an abstract array for contents ?
As far as initializing
contents, I think what you have is the best you can do. If there way a way,ArrayListwould probably do it (line 132: http://www.docjar.com/html/api/java/util/ArrayList.java.html)But when you say “the contents have just have the methods inherited from the Object class”, I’m assuming you mean that you can only access methods like
toStringandequalswhen you are working with a T instance in your code, and I’m guessing this is the primary problem. That’s because you’re not telling the compiler anything about what aTinstance is. If you want to access methods from a particular interface or type, you need to put a type constraint onT.Here’s an example:
So now you can access methods other than those inherited from
Object.