You can't create an array of a parametrized type (except unbounded wildcard types). Consider using a List
instead:
List<WeakReference<String>> testWR2 = new ArrayList<>();
This restriction on arrays is necessary for type safety reasons. For instance, consider the example given here, which shows what would happen if arrays of parametrized types were allowed:
// Not really allowed.
List<String>[] lsa = new List<String>[10];
Object o = lsa;
Object[] oa = (Object[]) o;
List<Integer> li = new ArrayList<Integer>();
li.add(new Integer(3));
// Unsound, but passes run time store check
oa[1] = li;
// Run-time error: ClassCastException.
String s = lsa[1].get(0);
If arrays of parameterized type were allowed, the previous example would compile without any unchecked warnings, and yet fail at run-time. We've had type-safety as a primary design goal of generics. In particular, the language is designed to guarantee that if your entire application has been compiled without unchecked warnings using javac -source 1.5
, it is type safe.