5

I know how to declare an individual WeakReference, but what about an array of them?

    WeakReference<String> testWR;
    testWR = new WeakReference<String>("Hello");

    String[] exStrArr;
    exStrArr = new String[5];

    WeakReference<String>[] testWR2;
    //not working
    testWR2 = new WeakReference<String>[5];
    testWR2 = new WeakReference<String>(new String())[5];
    testWR2 = new WeakReference<String>()[5];

Could someone please tell me the proper syntax here? I'd sure appreciate it =)

arshajii
  • 118,519
  • 22
  • 219
  • 270
codingNewb
  • 473
  • 1
  • 6
  • 20

1 Answers1

4

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.

arshajii
  • 118,519
  • 22
  • 219
  • 270