【发布时间】:2015-05-03 13:17:52
【问题描述】:
private static void genericArrayTest() {
ArrayList<? extends Exception>[] exceptionListArray = new ArrayList[10];
Object[] exceptionObjectListArray = exceptionListArray;
ArrayList<String> wrongArrayList = new ArrayList<String>();
wrongArrayList.add("String One");
ArrayList<NullPointerException> exceptionList = new ArrayList<>();
ArrayList rawList = new ArrayList();
exceptionListArray[0] = exceptionList;
//exceptionListArray[0] = wrongArrayList; // Compile error?
//exceptionListArray[0] = rawList;
exceptionObjectListArray[0] = wrongArrayList;
// No compile time error, there is no ArrayStoreException why ?
ArrayList<? extends Exception> list = exceptionListArray[0]; // No exception here as well ??
Exception e = list.get(0);
// Exception only when accessing data, why not ArrayStoreException when we stored wrong list ??
System.out.println();
}
谁能解释一下这是怎么回事?
谷歌搜索说下面的数组声明是允许的ArrayList<Exception>[] exceptionListArray = new ArrayList[10];
但不是这个 ArrayList<Exception>[] exceptionListArray = new ArrayList<Exception>[10];
这两个声明有什么区别?为什么一个不允许另一个?
Creating an array to store generic types in Java 讨论如何创建泛型数组。但是这个问题不是关于如何创建泛型数组,而是关于为什么在运行时不抛出 ArrayStoreException 以及 java 中泛型数组创建语法的差异
【问题讨论】:
-
在此处查看您的最后一个问题:stackoverflow.com/a/16415586/986169。关于 exceptionObjectListArray,它被声明为 Object 类型的数组。因此,任何扩展 Object 的类型的数组都可以分配给它。
-
@giorashc 从上面的链接,我进入了 - docs.oracle.com/javase/tutorial/java/generics/…。它说“如果允许参数化列表的数组,代码将无法抛出所需的 ArrayStoreException”。但是,它现在也发生了,上面的代码块正确吗?所以问题是 java 通过允许 'ArrayList
[] exceptionListArray = new ArrayList[10]; 实现了什么? ' ? -
我不认为这是完全重复的,因为这个问题询问的是 ArrayStoreException。