As far as initializing contents
, I think what you have is the best you can do. If there way a way, ArrayList
would 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 toString
and equals
when 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 a T
instance is. If you want to access methods from a particular interface or type, you need to put a type constraint on T
.
Here's an example:
interface Foo {
int getSomething();
void setSomethingElse(String somethingElse);
}
public class TestClass<T extends Foo> implements AbstractDataType<T> {
T[] contents;
public TestClass(int length) {
this.contents = (T[])new Object[length];
}
public void doSomethingInteresting(int index, String str) {
T obj = contents[index];
System.out.println(obj.getSomething());
obj.setSomethingElse(str);
}
}
So now you can access methods other than those inherited from Object
.