9
Generic Java 21/2-2003

Generic Java

Embed Size (px)

DESCRIPTION

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. - PowerPoint PPT Presentation

Citation preview

Page 1: Generic Java

Generic Java

21/2-2003

Page 2: Generic Java

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

Page 3: Generic Java

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

Page 4: Generic Java

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

Page 5: Generic Java

Assigning type parameters in GJclass 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();}

}

Page 6: Generic Java

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>

Page 7: Generic Java

Invariant subtyping

• Not allowed:

• Collection<object> c = new Collection<String>();

• Allowed:

• Collection<String> = new LinkedList<String>();

Page 8: Generic Java

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

Page 9: Generic Java

Consistency with legacy code

• translates into normal-looking Java code

• raw types

• retrofitting

• unchecked warnings