Java Reference
In-Depth Information
}
Although 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 para-
meter 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 it, let's try it.
TRY IT OUT: A Wildcard Array
You can modify the previous TryWildcard example to demonstrate using a wildcard type in an array:
public class TryWildCardArray {
public static void main(String[] args) {
BinaryTree<?>[] trees = {new BinaryTree<Integer>(), new
BinaryTree<String>()};
LinkedList<?>[] lists = new LinkedList<?>[trees.length];
int[] numbers = new int[30];
for(int i = 0 ; i < numbers.length ; ++i) {
numbers[i] = (int)(1000.0*Math.random());
// Random integers
0 to 999
}
// List starting integer values
int count = 0;
System.out.println("Original values are:");
for(int number : numbers) {
System.out.printf("%6d", number);
if(++count%6 == 0) {
Search WWH ::




Custom Search