java – 声明一个WeakReferences数组?
作者:互联网
我知道如何声明一个单独的WeakReference,但是它们的数组呢?
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];
有人可以告诉我这里的正确语法吗?我肯定会欣赏它=)
解决方法:
您无法创建参数化类型的数组(无限通配符类型除外).考虑使用List
代替:
List<WeakReference<String>> testWR2 = new ArrayList<>();
出于类型安全原因,这种对阵列的限制是必要的.例如,考虑给出的示例here,其中显示了如果允许参数化类型的数组会发生什么:
// 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.
标签:java,weak-references 来源: https://codeday.me/bug/20190624/1279528.html