The difference between arrays and generic types is
--The sequence is covariant and the generic type is invariant --Arrays are concrete (know their element types at run time and enforced), but generics are erasers (enforce type constraints only at compile time and discard type information at runtime).
E, ``` List
, and
List `` are technically known as nonreifiable types. Intuitively, a non-representable type is a type whose run-time representation is less informative than its compile-time representation. The only parameterized types that can be embodied are non-boundary wildcard types such as ``
List >` `` And `` `Map ,?>` ``. It is permissible to generate arrays of non-boundary wildcard type, but it is rarely useful.
Prohibiting the generation of generic sequences can be annoying. For example, generic types are generally unable to return an array of their element types.
It also means that you may get confusing warnings when using variadic methods in combination with generic types. That's because every time you call a variadic method, an array is generated to hold the variadic parameters.
(In the code below, args corresponds to that)
static int sum(int... args) {
int sum = 0;
for (int arg : args) {
sum += arg;
}
return sum;
}
If the element types of this array are not representable, you will be warned. There is little you can do about a warning other than suppressing it and not mixing generics and variadic arguments in your API.
If you get a generic sequence generation error, the best solution is usually to use the collection type List <E>
rather than the array type ```E [] ``
.
You may sacrifice some performance or brevity, but instead get better type safety and interoperability.
Recommended Posts