Generics for Dummies 
...or how to shoot an elephant 
from five feet, and miss! 
Knut Mork – 22.2.2005
"The increase in complexity is increasing, 
in part because of the natural, inevitable trend of technology 
to put together ever-more powerful solutions 
to problems we never realized we had.” 
Donald Norman
Traditional example 
List myIntList = new ArrayList(); 
myIntList.add(new Integer(0)); 
Integer x = (Integer) myIntList.iterator().next(); 
Same example using generics 
List<Integer> myIntList = new ArrayList<Integer>(); 
myIntList.add(new Integer(0)); 
Integer x = myIntList.iterator().next();
Excerpt from java.util: 
public interface List<E> { 
void add(E x); 
Iterator<E> iterator(); 
} 
public interface Iterator<E> { 
E next(); 
boolean hasNext(); 
}
• What ? 
– To abstract over types 
• Why ? 
– Safer code, eliminate run-time checks 
– Strong typing (not loose info) 
– Remove (visible) down-casting 
– Reduce awful, but necessary javadoc comments 
– Increase the indend of your code/interface 
– Others ? 
• Where ? 
– Collections, reflection (but problems with impl), others ? 
• When ? 
– Introduced in Java 1.5
No more casting ? 
Basket<Fruit> basket = new Basket<Fruit>(); 
basket.addElement(new Apple()); 
Apple apple = (Apple) basket.pickElement();
Simple, right? 
... wrong!
“Any fool can write code that a computer can understand. 
Good programmers write code that humans can understand.” 
Martin Fowler
Real example from java.util.Collections: 
public static <T extends Object & 
Comparable<? super T>> max(Collection<? extends T> coll) 
public static Object max(Collection coll) JDK 1.5 
JDK 1.4
Example - subtyping 
List<String> ls = new ArrayList<String>(); 
List<Object> lo = ls; 
lo.add(new Object()); 
String s = ls.get(0);
Example - subtyping 
List<String> ls = new ArrayList<String>(); 
List<Object> lo = ls; // compile-time error 
lo.add(new Object()); 
String s = ls.get(0);
Traditional example2 
void printCollection(Collection c) { 
Iterator i = c.iterator(); 
for(k = 0; k < c.size(); k++) { 
System.out.println(i.next()); 
} 
} 
Same example2 using generics 
void printCollection(Collection<Object> c) { 
for(Object e : c) { 
System.out.println(e); 
} 
}
Traditional example2 
void printCollection(Collection c) { 
Iterator i = c.iterator(); 
for(k = 0; k < c.size(); k++) { 
System.out.println(i.next()); 
} 
} 
Same example2 using generics 
void printCollection(Collection<?> c) { 
for(Object e : c) { 
System.out.println(e); 
} 
}
But, on the other hand... 
Collection<?> c = new ArrayList<String>(); 
c.add(new Object()); // compile-time error
It gets worse... 
”The single biggest enemy of reliability 
(and perhaps software quality in general) 
is complexity.” 
Bertrand Meyer
Bounded Wildcards 
public void eatAll (List<Fruit> fruites) { 
for (Fruit f: fruites) { 
f.eat(this); 
} 
} 
public void eatAll(List<? extends Fruit> fruites) { 
... 
}
Bounded Wildcards 
public void addBanana(List<? extends Fruit> fruites) { 
fruites.add(0, new Banana()); 
}
Bounded Wildcards 
public void addBanana(List<? extends Fruit> fruites) { 
fruites.add(0, new Banana()); // compile-time error 
}
...a lot worse... 
"Once a satisfactory product has been achieved, 
further change may be counterproductive, 
especially if the product is successful. 
You have to know when to stop.” 
Donald Norman
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic version: 
static void fromArrayToCollection(Object[] a, Collection<?> c) { 
for (Object o : a) { 
c.add(o); 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic version: 
static void fromArrayToCollection(Object[] a, Collection<?> c) { 
for (Object o : a) { 
c.add(o); // compile-time error 
} 
}
Example 3 
static void fromArrayToCollection(Object[] a, Collection c) { 
for (Object o : a) { 
c.add(o); 
} 
} 
Generic working version: 
static <T> void fromArrayToCollection(T[] a, Collection<T> c) { 
for (T o : a) { 
c.add(o); 
} 
}
”Under the hood” 
”When simple things need instruction, 
it is a certain sign of poor design.” 
Donald Norman
Traditional example 
List myIntList = new ArrayList(); 
myIntList.add(new Integer(0)); 
Integer x = (Integer) myIntList.iterator().next(); 
Same example using generics 
List<Integer> myIntList = new ArrayList<Integer>(); 
myIntList.add(new Integer(0)); 
Integer x = myIntList.iterator().next();
List <String> l1 = new ArrayList<String>(); 
List<Integer> l2 = new ArrayList<Integer>(); 
System.out.println(l1.getClass() == l2.getClass()); 
Output result ?
Collection cs = new ArrayList<String>(); 
if(cs instanceof Collection<String>) {...} 
Output result ?
Legacy code interoperability 
"You must not give the world what it asks for, 
but what it needs.” 
Edsger Dijkstra
Using legacy code in 1.5 
List fruitList1 = new ArrayList<Fruit>(); 
fruitList1.add(new Apple()); // warning 
List fruitList2 = new ArrayList(); 
fruitList2 = juggle(fruitList2); // warning 
List<Fruit> fruitList3 = new ArrayList<Fruit>(); 
fruitList3 = eat(fruitList3); // warning 
public List eat(List fruits) {...} 
public List<Fruit> juggle(List<Fruit> fruits) {...}
Using legacy code in 1.5 
public String loophole(Integer x) { 
List<String> ys = new ArrayList<String>(); 
List xs = ys; 
xs.add(x); // compile-time unchecked warning 
return ys.iterator().next(); 
}
Example of warnings given: 
Unsafe type operation: 
Should not assign expression of raw type List to type List<Foo>. 
References to generic type List<E> should be parameterized. 
Unsafe type operation: 
The method bar(List<Foo>) in the type SimpleExample should not 
be applied for the arguments (List). References to generic types 
should be parameterized.
...and even worse... 
"Once a satisfactory product has been achieved, 
further change may be counterproductive, 
especially if the product is successful. 
You have to know when to stop.” 
Donald Norman
• A type parameter cannot be referenced in a static context 
• Runtime type check with instanceof and casting on generic types have no meaning 
• Arrays of generic types are not permitted 
• For overloading, it is not enough to use wildcards for formal parameter types 
• Generic classes can be extended 
– The subclass provides the actual type parameters for the superclass 
• For overriding, the return type of the method in the subclass can now be identical or 
a subtype of the return type of the method in the superclass 
• A generic class cannot be a subclass of Throwable 
• Type parameters are allowed in the throws clause, but not for the parameter of the 
catch block 
• Varargs with a parameterized type are not legal
Introduction of characters with new special meaning 
<, > ? T, E, ... 
super & 
”Programs must be written for people to read, 
and only incidentally for machines to execute.” 
Abelson and Sussman
Which ones will compile ? 
a) Basket b = new Basket(); 
b) Basket b1 = new Basket<Fruit>(); 
c) Basket<Fruit> b2 = new Basket<Fruit>(); 
d) Basket<Apple> b3 = new Basket<Fruit>(); 
e) Basket<Fruit> b4 = new Basket<Apple>(); 
f) Basket<?> b5 = new Basket<Apple>(); 
g) Basket<Apple> b6 = new Basket<?>();
Thoughts and comments 
Anyone ? 
Is this a good thing or not ? 
Is it an important feature of the language ? 
What if this was included in the first version ? 
Would the design be different/easier ? 
Would users use it differently ? 
When should we use it ? If we should, that is! 
Why can’t we find other good examples, but the collection ones ?
Still interested ? 
• Intro paper: 
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf 
• Angelika’s F.A.Q. 
http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html
”There are two ways of constructing a software design: 
One way is to make it so simple 
that there are obviously no deficiencies, 
and the other way is to make it so complicated 
that there are no obvious deficiencies. 
The first method is far more difficult.” 
C. A. R. Hoare

Java Generics for Dummies

  • 1.
    Generics for Dummies ...or how to shoot an elephant from five feet, and miss! Knut Mork – 22.2.2005
  • 2.
    "The increase incomplexity is increasing, in part because of the natural, inevitable trend of technology to put together ever-more powerful solutions to problems we never realized we had.” Donald Norman
  • 3.
    Traditional example ListmyIntList = new ArrayList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next(); Same example using generics List<Integer> myIntList = new ArrayList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();
  • 4.
    Excerpt from java.util: public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); }
  • 5.
    • What ? – To abstract over types • Why ? – Safer code, eliminate run-time checks – Strong typing (not loose info) – Remove (visible) down-casting – Reduce awful, but necessary javadoc comments – Increase the indend of your code/interface – Others ? • Where ? – Collections, reflection (but problems with impl), others ? • When ? – Introduced in Java 1.5
  • 6.
    No more casting? Basket<Fruit> basket = new Basket<Fruit>(); basket.addElement(new Apple()); Apple apple = (Apple) basket.pickElement();
  • 7.
  • 8.
    “Any fool canwrite code that a computer can understand. Good programmers write code that humans can understand.” Martin Fowler
  • 9.
    Real example fromjava.util.Collections: public static <T extends Object & Comparable<? super T>> max(Collection<? extends T> coll) public static Object max(Collection coll) JDK 1.5 JDK 1.4
  • 10.
    Example - subtyping List<String> ls = new ArrayList<String>(); List<Object> lo = ls; lo.add(new Object()); String s = ls.get(0);
  • 11.
    Example - subtyping List<String> ls = new ArrayList<String>(); List<Object> lo = ls; // compile-time error lo.add(new Object()); String s = ls.get(0);
  • 12.
    Traditional example2 voidprintCollection(Collection c) { Iterator i = c.iterator(); for(k = 0; k < c.size(); k++) { System.out.println(i.next()); } } Same example2 using generics void printCollection(Collection<Object> c) { for(Object e : c) { System.out.println(e); } }
  • 13.
    Traditional example2 voidprintCollection(Collection c) { Iterator i = c.iterator(); for(k = 0; k < c.size(); k++) { System.out.println(i.next()); } } Same example2 using generics void printCollection(Collection<?> c) { for(Object e : c) { System.out.println(e); } }
  • 14.
    But, on theother hand... Collection<?> c = new ArrayList<String>(); c.add(new Object()); // compile-time error
  • 15.
    It gets worse... ”The single biggest enemy of reliability (and perhaps software quality in general) is complexity.” Bertrand Meyer
  • 16.
    Bounded Wildcards publicvoid eatAll (List<Fruit> fruites) { for (Fruit f: fruites) { f.eat(this); } } public void eatAll(List<? extends Fruit> fruites) { ... }
  • 17.
    Bounded Wildcards publicvoid addBanana(List<? extends Fruit> fruites) { fruites.add(0, new Banana()); }
  • 18.
    Bounded Wildcards publicvoid addBanana(List<? extends Fruit> fruites) { fruites.add(0, new Banana()); // compile-time error }
  • 19.
    ...a lot worse... "Once a satisfactory product has been achieved, further change may be counterproductive, especially if the product is successful. You have to know when to stop.” Donald Norman
  • 20.
    Example 3 staticvoid fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } }
  • 21.
    Example 3 staticvoid fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic version: static void fromArrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); } }
  • 22.
    Example 3 staticvoid fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic version: static void fromArrayToCollection(Object[] a, Collection<?> c) { for (Object o : a) { c.add(o); // compile-time error } }
  • 23.
    Example 3 staticvoid fromArrayToCollection(Object[] a, Collection c) { for (Object o : a) { c.add(o); } } Generic working version: static <T> void fromArrayToCollection(T[] a, Collection<T> c) { for (T o : a) { c.add(o); } }
  • 24.
    ”Under the hood” ”When simple things need instruction, it is a certain sign of poor design.” Donald Norman
  • 25.
    Traditional example ListmyIntList = new ArrayList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next(); Same example using generics List<Integer> myIntList = new ArrayList<Integer>(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();
  • 26.
    List <String> l1= new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getClass()); Output result ?
  • 27.
    Collection cs =new ArrayList<String>(); if(cs instanceof Collection<String>) {...} Output result ?
  • 28.
    Legacy code interoperability "You must not give the world what it asks for, but what it needs.” Edsger Dijkstra
  • 29.
    Using legacy codein 1.5 List fruitList1 = new ArrayList<Fruit>(); fruitList1.add(new Apple()); // warning List fruitList2 = new ArrayList(); fruitList2 = juggle(fruitList2); // warning List<Fruit> fruitList3 = new ArrayList<Fruit>(); fruitList3 = eat(fruitList3); // warning public List eat(List fruits) {...} public List<Fruit> juggle(List<Fruit> fruits) {...}
  • 30.
    Using legacy codein 1.5 public String loophole(Integer x) { List<String> ys = new ArrayList<String>(); List xs = ys; xs.add(x); // compile-time unchecked warning return ys.iterator().next(); }
  • 31.
    Example of warningsgiven: Unsafe type operation: Should not assign expression of raw type List to type List<Foo>. References to generic type List<E> should be parameterized. Unsafe type operation: The method bar(List<Foo>) in the type SimpleExample should not be applied for the arguments (List). References to generic types should be parameterized.
  • 32.
    ...and even worse... "Once a satisfactory product has been achieved, further change may be counterproductive, especially if the product is successful. You have to know when to stop.” Donald Norman
  • 33.
    • A typeparameter cannot be referenced in a static context • Runtime type check with instanceof and casting on generic types have no meaning • Arrays of generic types are not permitted • For overloading, it is not enough to use wildcards for formal parameter types • Generic classes can be extended – The subclass provides the actual type parameters for the superclass • For overriding, the return type of the method in the subclass can now be identical or a subtype of the return type of the method in the superclass • A generic class cannot be a subclass of Throwable • Type parameters are allowed in the throws clause, but not for the parameter of the catch block • Varargs with a parameterized type are not legal
  • 34.
    Introduction of characterswith new special meaning <, > ? T, E, ... super & ”Programs must be written for people to read, and only incidentally for machines to execute.” Abelson and Sussman
  • 35.
    Which ones willcompile ? a) Basket b = new Basket(); b) Basket b1 = new Basket<Fruit>(); c) Basket<Fruit> b2 = new Basket<Fruit>(); d) Basket<Apple> b3 = new Basket<Fruit>(); e) Basket<Fruit> b4 = new Basket<Apple>(); f) Basket<?> b5 = new Basket<Apple>(); g) Basket<Apple> b6 = new Basket<?>();
  • 36.
    Thoughts and comments Anyone ? Is this a good thing or not ? Is it an important feature of the language ? What if this was included in the first version ? Would the design be different/easier ? Would users use it differently ? When should we use it ? If we should, that is! Why can’t we find other good examples, but the collection ones ?
  • 37.
    Still interested ? • Intro paper: http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf • Angelika’s F.A.Q. http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html
  • 38.
    ”There are twoways of constructing a software design: One way is to make it so simple that there are obviously no deficiencies, and the other way is to make it so complicated that there are no obvious deficiencies. The first method is far more difficult.” C. A. R. Hoare

Editor's Notes

  • #5 Fra det første eksemplet, hvordan signatur klassene/interfacene som ble brukt blir definert
  • #6 Java var ikke de første til å introdusere denne språk-featuren, vis kanskje med eksempel med templates i c++
  • #7 Skriv ned resten av deklarasjonene på tavla... Eller ta dem høyt! Et annet tilfelle på casting er ved uthenting av objekter fra JNDI-tre
  • #9 Vis FAQ-siden til Angelika (http://www.langer.camelot.de/GenericsFAQ/JavaGenericsFAQ.html) Vis javadoc på collection api’et (http://java.sun.com/j2se/1.5.0/docs/api/java/util/Collections.html)
  • #10 Hva er navnet på metoden ? Hva tar metoden som parameter ??? Hvorfor er den blitt så kompleks ? Pga bakoverkomp – skal ikke være mer begrensende enn tidligere versjoner
  • #11 FØRSTE PROBLEM! En og en linje...
  • #12 Ta på tavla – G&amp;lt;Foo&amp;gt; !subtype G&amp;lt;Bar&amp;gt;, selv om Foo subtype Bar (Bruk Basket/fruit/apple eksemplet)
  • #13 Hva er feil med det nederste eksemplet ? Collection of unknown: Collection&amp;lt;?&amp;gt;
  • #14 Hva er feil med det nederste eksemplet ? Collection of unknown: Collection&amp;lt;?&amp;gt; Wildcard type Vi kan fortsatt lese elementer og gi dem typen Object. Men...
  • #15 Men, å assigne et Object til resultatet av get() er lov!
  • #17 Før denne slide, gi eksempel-koden først Hva betyr den første metoden ? Jo, f.eks. Kan vi ikke kalle på denne med List&amp;lt;Apple&amp;gt; (Apple er subtype av Fruit)
  • #18 Hvorfor gir denne feil ? Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana Tegn bokser klasse-hierarki
  • #19 Hvorfor gir denne feil ? Typen til den andre parameteren er en ukjent subtype av Fruit. Denne behøver ikke nødvendigvis være en supertype til Banana Tegn bokser klasse-hierarki
  • #21 Spør publikum hvordan denne kan løses, og begynn å skriv metoden på tavla ...men bør overskriften egentlig være her ? Det kan være tull å introdusere alle ”ordene” i generics-ordboka... Kanskje lettere å bare vise de ulike tingene ???
  • #22 Spør publikum hvordan denne kan løses
  • #23 Spør publikum hvordan denne kan løses
  • #24 Kan man nå f.eks. ha en array av Stringer og en Collection av Objecter ? JA! T definisjonen kan f.eks. også ha ”extends” og andre ting i seg!
  • #25 Hvorfor er det nødvendig å kunne (eller bare å si) noe om dette her ? Svar: Dårlig design/implementasjonen påvirker interfacet!
  • #26 Vis hvordan koden ser ut etter å ha kjørt JAD. Erasior
  • #27 True
  • #28 Hvorfor gir denne feil ?
  • #30 Unchecked warnings will occur
  • #31 Vil gi feil i runtime!
  • #34 Hentet fra foredrag på javazone... Var så morsom (fordi man blir bare helt oppgitt) at jeg måtte ta den med... ...og på neste slide til vedkommende, så står det med store bokstaver: ”GENERIC FUN HAS JUST BEGUN” Why not ? Unntak er kjedelig (les: gjør ting vanskeligere) Årsaken til noen her er erasure valget!
  • #35 Kanskje bedre å tegne på tavla Som er nesten definisjonen på økt kompleksitet/økt vanskelighet. Og dette er bare for generics... Andre så som ”:” er også lagt til i 1.5
  • #36 Teste litt kunnskaper helt til slutt