Declare an array of WeakReferences?

I know how to declare a separate one 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];

Can someone please tell me the correct syntax here? I would appreciate it =)

+4
source share
1 answer

You cannot create an array of parameterized type (except for unlimited wildcard types). Use instead List:

List<WeakReference<String>> testWR2 = new ArrayList<>();

This restriction on arrays is necessary for type safety reasons. For example, consider the following example, which shows what happens if arrays of parameterized types are 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);

, - . . , , , , , javac -source 1.5, .

+4

Source: https://habr.com/ru/post/1532755/


All Articles