Responding to a question about this here: https://stackoverflow.com/a/312969/
I tried to do the following:
Comparator<String>[] comparators = new Comparator[] {...};
It works! But the following:
Comparator<String>[] comparators = new Comparator<String>[] {...};
On the relevant question, I made the assumption:
I assume that initially the contract with the array could be something like this:
If you create an array of type X, you NEVER NEVER put something in it that IS-NOT-AN X. If you try, you will get an ArrayStoreException
Thus, creating arrays with creating generics will result in a rule like:
If you create an array of type X<Y>
, you NEVER can ever put anything that is NOT-NOT-A X. If you try, you will get an ArrayStoreException. But you can add objects X<Y>
and X<Z>
due to erasing styles!
But thinking about it, it would really be a problem:
Comparator<String>[] comparators = new Comparator<String>[] {...};
I really don't understand why this is not possible, since using such a thing:
- Check classes inserted at runtime
- Check the class type inserted at compile time
Finally, we can use an array with a typical type reference and because of the impossibility of creating an array with a common type, I think many people do not even know that this is possible.
I'm just wondering if anyone knows the reason for this choice?
This is a bit like forcing people to use List<String> = new ArrayList();
instead of using List<String> = new ArrayList<String>();
dimitrisli you gave a good example from the famous book of Joshua Bloch. As you have explained this, it is dangerous to use both shared arrays + covariance and cause a ClassCastException, while we expect an ArrayStoreException from the array using covariance.
But please note that it is still legal and leads to the same:
List<String>[] stringLists = new List[1]; List<Integer> intList = Arrays.asList(42); Object[] objects = stringLists; objects[0] = intList; String s = stringLists[0].get(0);
However, when compiling, it throws a warning about unverified warnings, and, as you noted, a ClassCastException at runtime.