90 likes | 229 Vues
Generic Java. 21/2-2003. What is generics?. To be able to assign type variables to a class These variables are not bound to any specific type until the declaration This makes it possible to write generic functions that will work with many different types Analogous to parametric types.
E N D
Generic Java 21/2-2003
What is generics? • To be able to assign type variables to a class • These variables are not bound to any specific type until the declaration • This makes it possible to write generic functions that will work with many different types • Analogous to parametric types
Java: The current situation • Utility classes with simulated generics • Ex. a container such as a Collection where all elements are treated as instances of type Object, regardless of their original types • While retrieving the elements it is necessary to cast them to their original types • This is inconvenient and error-prone
Motivation for GJ • avoid having to write casts • make it possible to catch cast errors at compile-time • should be compatible with the unextended java language
class Pair <A,B> { private A element1; private B element2; public Pair (A element1, B element2) { this.element1 = element1; this.element2 = element2; } public A getElement1() { return element1; } public B getElement2() { return element2; } } class Test { public static void main (String[] args) { Pair <String, Integer> shoe; shoe = new Pair <String, Integer > (”Addidas”, new Integer (”38”)); String name = shoe.getElement1(); Integer size = shoe.getElement2(); } } Assigning type parameters in GJ
Assigning • it is not possible to assign an object to another object of the same type, but with a different type parameter • it will, for example, cause a compile error if you try to assign Pair <String, Integer> to Pair <String, Character>
Invariant subtyping • Not allowed: • Collection<object> c = new Collection<String>(); • Allowed: • Collection<String> = new LinkedList<String>();
Translating GJ • the translation erases the type parameters, maps type variables to their bounds, inserts the appropriate casts, and bridge methods • the GJ-compiler translates the parameterized source code to get the generic effect with features already present in Java (but in a type-safe manner) • the translation is homogeneous • the type parameters are not available run-time
Consistency with legacy code • translates into normal-looking Java code • raw types • retrofitting • unchecked warnings