O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

13.6. Arrays and Parameterized Types

Arrays of elements that are of a specific type produced from a generic type are not allowed. For example, although it looks quite reasonable, the following statement is not permitted and will result in a compiler error message:

LinkedList<String>[] lists = new LinkedList<String>[10];   // Will not compile!!!

Although you can declare a field in a generic type by specifying the type using a type variable, you are not allowed to create arrays of elements using a type variable. For example, you can define a data member like this:

public class MyType<T> {
  // The methods and data members of the type...
  private T[] data;                                        // This is OK
}

While defining the data field as being of type T[] is legal and will compile, the following is not legal and will not compile:

public class MyType<T> {
  // Constructor
  public MyType() {
    data = new T[10];                                      // Not allowed!!
  }

  // The methods and data members of the type...
  private T[] data;                                        // This is OK
}

In the constructor you are attempting to create an array of elements of the type given by the type variable T, and this is not permitted.

However, you can define arrays of elements of a generic type where the element type is the result of an unbounded wildcard type argument. For example, you can define the following array:

LinkedList<?>[] lists = new LinkedList<?>[10];             // OK

Each element in the array can store a reference to any specific LinkedList<> type, and they could all be different types. Just so that you can believe ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required