Creating a generic array in java

Possible duplicate:
Create an instance of a generic type in Java? Java how to create Generic Array

I am trying to create a generic type class. 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 content only has methods inherited from Object class

. How do I create an abstract array for content?

+1


source to share


4 answers


In terms of initialization contents

, I think you have the best you can do. If it were, ArrayList

it probably would (line 132: http://www.docjar.com/html/api/java/util/ArrayList.java.html )

But when you say "content only has methods inherited from Object class", I assume you mean that you can only use methods like toString

and equals

when you are working with an instance of T in your code, and I I guess this is the main problem. This is because you are not telling the compiler what an instance is T

. If you want to access methods from a specific interface or type, you need to set the type constraint to 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

.

+6


source


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



+1


source


I believe that in any method that accesses content, you need to specify them as a type T

. The main reason for this is that, as an array of objects, Java treats the content as objects to host it. Thus, while it contents

may be an array T

, it is still just an array of type Object

.

0


source


What 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);
}

      

0


source







All Articles