Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java Generics.

Similar presentations


Presentation on theme: "Java Generics."— Presentation transcript:

1 Java Generics

2 What is It? Recall: Parametric Polymorphism, a kind of universal polymorphism. Abstraction over types, using the array metaphor. In e.g., Pascal, if you have a type T, then there is also a type “Array of T” Java Generics: the Java name and adaptation of the general Parametric Polymorphism concept. Common Example: (in Java and other languages) containers Containers Type Safety Without Generics: runtime with ClassCastException With Generics: compile time. Readability When you see a list, you know of what! List<Integer> myIntList = new LinkedList<Integer>(); Generic Interface Generic class Implementing this Interface

3 Generics – Before and After
List myIntList = new ArrayList(10); myIntList.add(new Integer(0)); Integer x = (Integer)myIntList.get(0); myIntList.add(new String("abc")); Integer y = (Integer)myIntList.get(1); Runtime exception List<Integer> myIntList = new ArrayList<Integer>(10); myIntList.add(new Integer(0)); Integer x = myIntList.get(0); myIntList.add(new String(“abc”)); No cast is needed Compile error With generics, the list knows what types it acts on.

4 Basic Generics Syntax public interface List <E> { void add(E x);
Iterator<E> iterator(); } public interface Iterator <E> { E next(); boolean hasNext(); formal type parameter In invocation, such as List<Integer>, all occurrences of the formal type parameter (E) are replaced by the actual type argument (Integer). Only object types are legal arguments Primitive types are not allowed Autoboxing can help Non-type parameters are not allowed

5 Generic Classes class Foo <T> { void method(T arg); }; Foo<Bar> fb = new Foo<bar>; fb.method(aBar); //OK fb.method(not_a_Bar); // compile error Foo is generic: Same behavior for any possible T (the type parameter) Single Source: only one foo.java Low maintence Single binary: only one foo.class No binary explosion (but imposes restrictions)

6 Generic Methods <T> T method(T arg); };
Bar b = method(aBar); //OK b = method(not_a_Bar);//Compile error The actual type parameter is not passed The compiler infers the type argument Compiler ensures arg and return are same type When the method is compiled On method calls

7 Bounded Type Parameters
class TreeMap< K extends Comparable<K> , V> { private static class Entry<K,V>{…}; private Entry<K,V> getEntry(K key) { while (p != null) { int cmp = k.compareTo(p.key); } }; Sets restrictions on the type parameter The extends keyword is used both for classes and interfaces Can have multiple bounds T extends Foo & Comparable<T>

8 Wildcards void method(Collection<Object> c);
Accepts Collection<Object> Is Collection<String> subtype of Collection<Object>? NO! generics are NOT covariant LinkedList<Object> objLst = new LinkedList<String>(); // compile error So, how do we declare m to work on any collection?

9 Wildcards void method(Collection<?> c); Collection of “unknown”
c.get() returns an Object C.add(o) is not allowed Exception: null, which is a member of every type. Read only usage in method body!

10 Bounded wildcards Upper bound: <? extends Foo>
Wildcard can be any subclass of Foo Including Foo itself void method(Collection<? extends Foo> c); As with unbounded wildcards, c is readonly. Lower bound: <? super Foo> Helps to rearrange arguments types E.g., Copy entries from source to destination, return the last one: T copySet( Set<T> source, Set<? super T> destination );

11 Bounded wildcards - Example
public abstract class Shape { public abstract void draw(Canvas c); } public class Circle extends Shape { private int x, y, radius; public void draw(Canvas c) { ... } } public class Rectangle extends Shape { private int x, y, width, height; public void draw(Canvas c) { ... } } public void drawAll( List<? extends Shape> shapes ) { //... }

12 Type Erasure Generics processing in Java Benefit of Erasure:
Check: type correctness Erase: all generic type information Compile: to byte code Benefit of Erasure: Binary compatibility with older libraries: List<String> is translated to type List (raw type ) Code compiled using a "pre-generics" class works correctly Code written using a "pre-generics" class still compiles and work Drawback of Erasure generic type information is not known at runtime List<Integer> and List<String> refer to List type variables cannot be used in new expressions Type is unknown at runtime

13 Type Erasure – (some of the) Rules
If a class doesn't use type parameters in its definition, erasure doesn't change the class definition. Parameterized types "drop" their type parameters. Every type parameter is mapped to the strongest type the compiler can reasonably assert. In the case of <T>, T is mapped to Object. In the case of <T extends Rentable>, T is mapped to Rentable. Casts are inserted wherever necessary, to ensure that the code compiles.

14 Erasure What is the “real” signature of Answer:
class Foo<T extends Number> { T m(Set<? Extends T> s){} }; class Foo { Number m(Set s){} };

15 Erasure and Multiple Bounds
Signature erases to the first type: class Foo<T extends Comparable<T> > { }; Erased type is Comparable class Foo<T extends Object & Comparable<T> > { }; Erased type is Object

16 Erasure - Loophole The compiler generates a warning Line 3
List<Integer> intList = new ArrayList<Integer> (); List wideOpen = intList; wideOpen.add(anObject); //loophole Integer i = intList.get(0); //runtime exception The compiler generates a warning Line 3 Just like code without Generics

17 Generic Arrays List<String>[] lsa = new List<String>[10];
Object[] oa = lsa; li = new ArrayList<Integer>(); li.add(new Integer(3)); oa[0] = li; String s = lsa[0].get(0); The array assignment in line 2 compiles as before, (List<String> is a subtype of Object) The assignment in line 5 succeeds at runtime since oa[0] has the dynamic type List, just like li

18 Generic Arrays Component type of Array can not be parameterized.
List<Foo>[] is not allowed! Arrays are covariant while generics are not!


Download ppt "Java Generics."

Similar presentations


Ads by Google