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();
}
Can someone please explain what is going on ?
Google search says below array declaration is allowed
ArrayList<Exception>[] exceptionListArray = new ArrayList[10];
but not this
ArrayList<Exception>[] exceptionListArray = new ArrayList<Exception>[10];
What is the difference between these two declaration & why one is allowed not other one?
Creating an array to store generic types in Java is talks about how to create generic array. But this question is not about how to create generic array, its about why ArrayStoreException is not thrown at runtime & difference in generic array creation syntax in java