Primitives in Generics
Gernot Neppert
mcnepp02 at googlemail.com
Thu Jul 8 23:28:03 PDT 2010
2010/7/8 Reinier Zwitserloot <reinier at zwitserloot.com>:
> You didn't mention my second snippet, which is a shame, because I included
> it because that's the one I'm confused about - how could you possibly write
> a compiler that detects there's a problem there?
> --Reinier Zwitserloot
>Snippet #2:
>public static List<T> createList(Class<T> type) { return new ArrayList<T>(); }
>public void test() {
> List<int> list = createList(int.class);
> list.add(10);
>}
OK, looks like you've found the big weak spot in my proposal ;-)
Even though the exact code from snippet #2 would not compile
(int.class is of type Class<Integer>, therefore the assignment to
List<int> is not valid), the snippet shows of course the fundamental
problem:
The use of primitive type parameters in all contexts is incompatible
with Type Erasure.
Thus, one would have to restrict the use; maybe something like this would do:
8. Type parameters of primitive type parameters may only be used in
the following contexts:
a) when declaring variables. Local variables or members may be
declared using a primitive type parameter, and optionally initialized
with null.
Example: List<int> list = null;
b) during implementation of a generic interface or a generic baseclass
by a class that specifies a concrete type for the type parameter.
Example: public class IntList implements List<int>
{
}
c) generic functions will never make use of primitive type parameters.
If you pass an instance of a generic class L<p> for a primitive type p
to a generic function paramerized by T over L<T>, the instance will be
automatically treated as L<P> with P the corresponding wrapper type
for p. (See paragraph 6. for assignment rules)
Example:
import java.util.Collections;
List<int> list = new IntList();
List<int> sorted = Collections.sort(list); // Will not compile
List<int> empty = Collections.emptyList(); // Will not compile
List<Integer> sorted = Collections.sort(list); // OK, list is passed
as List<Integer> here.
More information about the lambda-dev
mailing list