Give an example how type safety could be compromised if it was legal to create arrays of parametrized types (but it is not legal).
Answer
You could create an array of lists of strings:
List<String>[] stringLists = new List<String>[1]; // this part is not legal and wouldn't compile
Because arrays are covariant, you can store the array into a variable of Object[] type and then store an element of type List<Integer> (or really List<anything>) as an element of the original array without causing ArrayStoreException because at runtime List<String> and List<Integer> are simply lists
So, we are in trouble - List<Integer> is stored where the compiler thought it was List<String>
Tags
#bloch-effective-java-2ed #java #java-generics
Question
Give an example how type safety could be compromised if it was legal to create arrays of parametrized types (but it is not legal).
Answer
?
Tags
#bloch-effective-java-2ed #java #java-generics
Question
Give an example how type safety could be compromised if it was legal to create arrays of parametrized types (but it is not legal).
Answer
You could create an array of lists of strings:
List<String>[] stringLists = new List<String>[1]; // this part is not legal and wouldn't compile
Because arrays are covariant, you can store the array into a variable of Object[] type and then store an element of type List<Integer> (or really List<anything>) as an element of the original array without causing ArrayStoreException because at runtime List<String> and List<Integer> are simply lists
So, we are in trouble - List<Integer> is stored where the compiler thought it was List<String>
If you want to change selection, open document below and click on "Move attachment"