Notes
Slide Show
Outline
1
Generics in Java 5
  • Maurice Naftalin
  • Morningside Light Ltd


  • Scottish Developers Java Day
  • 11th March 2005
2
Lots of New Language Features
in Java 5…
  • Annotations
  • Autoboxing
  • Enhanced for-loop
  • Enums
  • Generics
  • Static import
  • Varargs
3
The new features work together…
  • List ints = Arrays.asList( new Integer[] { new Integer(1), new Integer(2), new Integer(3) } );
  • int sum = 0;
  • for (Iterator it = ints.iterator(); it.hasNext();){
  •   int n = ((Integer)it.next()).intValue();
  •   sum += n;
  • }
  • assert sum == 6;
4
…varargs…
  • List ints = Arrays.asList(                 new Integer(1), new Integer(2), new Integer(3)   );
  • int sum = 0;
  • for (Iterator it = ints.iterator(); it.hasNext();){
  •   int n = ((Integer)it.next()).intValue();
  •   sum += n;
  • }
  • assert sum == 6;
5
…autoboxing…
  • List ints = Arrays.asList(
  •         1 ,             2 ,             3    );
  • int sum = 0;
  • for (Iterator it = ints.iterator(); it.hasNext();){
  •   int n = ((Integer)it.next());
  •   sum += n;
  • }
  • assert sum == 6;
6
…
  • List          ints = Arrays.asList( 1, 2, 3 );


  • int sum = 0;
  • for (Iterator it = ints.iterator(); it.hasNext();){
  •   int n = (Integer)it.next();
  •   sum += n;
  • }
  • assert sum == 6;
7
…generics…
  • List<Integer> ints = Arrays.asList( 1, 2, 3 );


  • int sum = 0;
  • for (Iterator it = ints.iterator(); it.hasNext();){
  •   int n =           it.next();
  •   sum += n;
  • }
  • assert sum == 6;
8
…foreach
  • List<Integer> ints = Arrays.asList( 1, 2, 3 );


  • int sum = 0;
  • for (      int n : ints                          ){
  •   sum += n;
  • }
  • assert sum == 6;
9
How did that work?
  • Pre-Java 5:



  • and quite frequently…
10
How does it work now?
  • In Java 5 we write:




  • and now…
11
Common operations are now typesafe
  • Detect misuse of collections at compile time
  • Customise collection classes
  • Reveal implicit type requirements of interfaces
  • Add control over argument validation
12
Customise Collection Classes
  • I want a sorted set of String
    • pre-Java 5:
13
Customise Collection Classes (continued)
  • with generics:
14
Reveal implicit type requirements of interfaces
  • interface Comparator {
  • public int compareTo( Object o1, Object o2 );
  • }
15
Add control over argument validation
  • class RootFactory {
  • static Object make(Class type) {
    if (!Root.class.isAssignableFrom(type))
    throw new IllegalArgumentException();
    return type.newInstance();
    ...
    }
  • }


  • Derived d =
    (Derived) RootFactory.make(Derived.class)
16
Add control over argument validation (continued)
17
But Java has always been able to do that!
  • Array accesses have always been statically typechecked…





  • …as far as possible…
18
Arrays are covariant
  • Integer extends Number
    implies that
  • Integer[] is a subtype of Number[]
  • The compiler can’t tell the run-time type of a Number[] variable
  • So assignments have to be checked at runtime
19
Covariance requires RTTI
  • Arrays carry type information at run-time


20
Generics can’t have RTTI
  • Generified code needs to be able to call non-generified (legacy) library methods
  • These methods have to accept generified objects
  • Overriding design aim: only one version of the core class libraries
21
Erasure
  • All parameterised type information removed before compilation
    • Type arguments are removed:



    •    becomes
22
Erasure (continued)
  • Type parameters replaced by Object*
23
So generic classes can’t be covariant
  • If we write
  • List<String> ls = new ArrayList<String>();
  • This doesn’t compile:
    • List<Object> lo = ls;
  • And we don’t it want to!  If it did we could write:
    • lo.add( new Object() );
    • String s = ls.get(0);
  • And we’d have to go back to run-time type-checking, array style
24
How will we do without covariance?
  • We still want to use polymorphism the way that arrays allow:
25
How will we do without covariance? (continued)
  • This won’t work:
26
Wildcards
  • But this will work:
27
Wildcards (continued)
  • The type expression
    • ? extends Shape
    • represents an arbitrary unknown
    • subtype of Shape
  • The type expression
    • ? super Shape
    • represents an arbitrary unknown
    • supertype of Shape
28
Using a wildcard type restricts access
  • A variable declared as
  •   List<? extends Number> listNumbers;
    • represents a collection of Number
    • subclass objects
  • So you can take things out of it
    • Number n = listNumbers.get(0);
  • But you can’t put anything into it
    • listNumbers.add(1);
29
Using a wildcard type restricts access (continued)
  • A variable declared as
  •   List<? super Integer> intsOrBigger;
    • represents a collection of objects of some
    • Integer superclass
  • So you can put things into it
    • intsOrBigger.add(1);
  • But you can only get some things out of it
    • Object o = intsOrBigger.get(0);
30
Bounded wildcards can work together
  • Collections is a utility class of generic collection methods:



  • Compiler infers types where necessary
31
Bounds work with type variables too
  • class Pair<S,T> {
  • private S first;
  • private T second;


  • <A extends S> void setFirst( Pair<A,?> p) { first = p.first;
  • }
  • ...
  • }
32
Erasure produces some surprises
  • You can declare a reference variable for an array of generic type:
    • T[] tArray;
  • But it won’t do you much good:
    • tArray = new T[10]; // illegal
  • instanceof doesn’t work as you might expect
    • o instanceof List<Long>// illegal
33
Erasure produces some surprises (continued)
  • Type inference may not always produce the result you wanted:
34
Conclusions
  • Generics provide type safety in new areas, and will give rise to new design idioms
  • Easy for the client programmer to use
    • Maybe easier than for the library designer
  • Erasure provides backward compatibility
    • Controversial in some quarters…
  • Java programmers need to understand generics now!


35
References
  • Introductory tutorial by Gilad Bracha (generics designer)
    • http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
  • Good set of links to web resources on generics
    • http://www.langer.camelot.de/Resources/Links/JavaGenerics.htm
  • FAQ comprehensively covering technical and usage issues
  •     http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html
  • Draft of the new Java Language Specification
    • http://java.sun.com/docs/books/jls/java_language-3_0-mr-spec.zip