1

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 ?

Community
  • 1
  • 1
Rahul
  • 38,533
  • 23
  • 65
  • 94

4 Answers4

6

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.

smjZPkYjps
  • 1,078
  • 7
  • 12
1

You cannot create a generic array in Java. As stated in the Java Language Specification, the mentioned rules state that "The rules above imply that the element type in an array creation expression cannot be a parameterized type, other than an unbounded wildcard."

Filipe Fedalto
  • 2,402
  • 1
  • 15
  • 20
0

I believe that in any method that accesses contents, you need to cast them as type T. The main reasoning for this is that as an Object array, Java looks at the contents as Objects to fit them in. So while contents might be an array of T, it still is just an array of type Object.

brandonsbarber
  • 374
  • 1
  • 3
  • 10
  • -1 for incorrect information: `contents[0]` already is of type `T`, casting it to `T` won't change a thing. – meriton Aug 27 '12 at 19:13
0

How do you think ArrayList.toArray and Arrays.copyOf do it?

See Array.newInstance.

public TestClass(Class<T> type, int length) {
    this.contents = Array.newInstance(type, length);
}
slavemaster
  • 194
  • 4