SlideShare a Scribd company logo
Generic Programming Seminar by  Gautam Roy  Debasish Sengupta <T> <E> <K, V>
Today’s Agenda Theoretical concept of Generic Programming. Generics in Java. Questions are welcome throughout our session.
What is Generic Programming? Raising the level of abstraction. What do we do when we program? We write a sequence of statements. What is the level of abstraction? We write at the level of source code. That gets translated directly into machine code, which is less abstract. <T> <E> <K, V>
With generic programming, the level of abstraction is higher. The source code is just a pattern. The actual machine code that comes out depends on how the pattern is “filled-in”. static <T> List<T> newList() { return new ArrayList<T>(); } Without knowing T, no machine code can be generated from the above. Summary: With normal programming, we can know the overview of low level code generated from just by looking at the source. With generic programming, the code is at a higher level. Need to know other things, like the type parameters.
So… Generic programming is programming that focuses on the algorithms and code at a higher level of abstraction that “normal” programming. Generic programming is a style of computer programming in which algorithms are written in terms of  to-be-specified-later  types that are then  instantiated  when needed for specific types provided as parameters
Path to Generic Programming Lifting : Lifting is the process of finding commonality among similar implementations of the same algorithm and then providing suitable abstractions so that a single, generic algorithm can cover many concrete implementations.
Path to Generic Programming(contd..) Lifting  is repeated until the generic algorithm has reached a suitable level of abstraction, where it provides maximal reusability while still yielding efficient implementations. The abstractions themselves are expressed as requirements on the parameters to the generic algorithm.
By-product of Generic Programming Concept : A  concept  contains a set of requirements that describe a family of abstractions, typically data types. Examples of concepts include  Iterator ,  Graph ,  Comparable  etc.
Format definition of  Concept Once many algorithms within a given problem domain have been lifted, we start to see patterns among the requirements. It is common for the same set of requirements to be required by several different algorithms. When this occurs, each set of requirements is bundled into a  concept .
Thus, the output of the Generic Programming process is not just a generic, reusable implementation, but a better understanding of the problem domain.
Lifting  in Action Consider the following two definitions of “max”. int max(int a, int b) {   if (a > b) return a;   else return b; } float max(float a, float b) {   if (a > b) return a;   else return b; } How can we lift this to create just one version? <T> T max(T a, T b) { if (a > b) return a; else return b; } Does it compile in Java latest  version?
Evolution of  Concept T needs to be Comparable so that we can compare various types. When we will write “max” for n number of elements then we need  Container  and also  Comparable . - Here Comparable is a  concept  here.
Lifted  version of “max” <T extends Comparable<? super T>> T max(T a, T b) { Comparable c1 = (Comparable) a; Comparable c2 = (Comparable) b; if  (c1.compareTo(c2) > 0)  return a; else return b; } - This code introduce the concept  Comparable.
Generics and Polymorphism One view of polymorphism is Ability of code to work with different types  Generic parameters and subtyping  Both mechanisms for accomplishing polymorphism Both support programming by abstracting from concrete types Polymorphism using generic types - parametric polymorphism Polymorphism using subtypes - subtype polymorphism
Generics in Java
Original team behind Java Generics Left to right: Philip Wadler, Martin Odersky, Gilad Bracha, Dave Stoutamire  Making Java easier to type, and easier to type
Generics in Java Use of raw type in Java List l = new ArrayList(); // 1 l.add(Integer.valueOf(0)); // 2 Integer x = (Integer) l.get(0); // 3 - Can you see the disadvantages of these raw type?
Use of generic type Same code with generics: List<Integer> l = new ArrayList<Integer>(); // 1 l.add(Integer.valueOf(0)); // 2 Integer x = l.get(0); // 3 And with Autoboxing and unboxing:  List<Integer> l = new ArrayList<Integer>(); // 1 l.add(0); // 2 int x = l.get(0); // 3
Advantages of generic type // Generic type: Good Collection<Coin> coinCollection = new ArrayList<Coin>(); coinCollection.add(new Stamp());  // Won’t compile ... for (Coin c : coinCollection) { ... } // Raw Type: Evil Collection coinCollection = new ArrayList(); coinCollection.add(new Stamp());  // Succeeds but should not ... for (Object o : coinCollection) { Coin c = (Coin) o;  // Throws exception at runtime ... }
Advantages of generic type ... Compile time error detection; more robust code Succinct and stylish coding practice. Less typing and repetition; adheres to DRY principle Reduce Accidental Complexity in code. Flexibility of API design.
Generic Class and Constructor public   class  Pair<T, S> {  private  T first;  private  S second;  public  Pair(T f, S s) {  first = f;  second = s;  } public  T getFirst() {  return  first; }  public  S getSecond() { return  second;  } public  String toString() {  return  &quot;(&quot; + first.toString() + &quot;, &quot; + second.toString() + &quot;)&quot;;  } } - here T and S are type variable or formal type parameter
Generic class in Action Pair<String, String> grade440 =  new  Pair<String, String>(&quot;mike&quot;, &quot;A&quot;); Pair<String, Integer> marks440 =  new  Pair<String, Integer>(&quot;mike&quot;, 100);  System.out.println(&quot;grade:&quot; + grade440.toString());  System.out.println(&quot;marks:&quot; + marks440.toString());
Generic interface Same as generic class public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } Lots of example in Java collection framework like List, Set, Map etc.
Type inference The automatic deduction of the type arguments of a generic method at compile time. List<T> l = new ArrayList<T>(); Does it compile in Java latest version?  public static <T> newList() { return new ArrayList<T>; } Does it compile in Java latest version?
Generic Methods A generic method can be invoked in two ways: Explicit type argument specification .  The type arguments are explicitly specified in a type argument list. Automatic type argument inference. The method is invoked like regular non-generic methods, that is, without specification of the type arguments.  In this case the compiler automatically infers the type arguments from the invocation context.   public  <T> Pair<T,T> twice(T value) {  return   new  Pair<T,T>(value, value);  }
Generic method in Action Explicit type argument: Pair<String, String> pair = this. <String> twice(&quot;Hello&quot;); Or using type inference Pair<String, String> pair =  twice (&quot;Hello&quot;); Explicit type argument  System.out.println(Utilities. <String> max(&quot;abc&quot;,&quot;xyz&quot;)); Or using type inference System.out.println(Utilities. max (&quot;abc&quot;,&quot;xyz&quot;));
Type parameter naming conventions E - Element (used extensively by the Java Collections Framework)  K - Key  N - Number  T - Type  V - Value  S,U,V etc. - 2nd, 3rd, 4th types
Generics and Wildcards The method  prints out all the elements in a collection: void printCollection(Collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) { System.out.println(i.next()); } } One  naive attempt at writing it using generics: void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); } }  -  Why it is inflexible?
Generics and Subtyping Arrays are  covariant  but generic types are  contravariant. That is,  List<String>  is not a subtype of  List<Object> Good for compile-time type safety, but inflexible Wildcard and bounded wildcard to the rescue
Wildcards to the rescue Correct method void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } } ? is wildcard type here . But what about this?  Collection<?> c = new ArrayList<String>(); c.add(new Object());
Example of Subtyping public interface Shop<T> { T buy(); void sell(T myItem); void buy(int numToBuy, Collection<T> myCollection); void sell(Collection<T> myLot); } class Model { } class ModelPlane extends Model { } class ModelTrain extends Model { }
Works Fine If You Stick to One Type // Individual purchase and sale Shop<ModelPlane> modelPlaneShop = ... ; ModelPlane myPlane = modelPlaneShop.buy(); modelPlaneShop.sell(myPlane); // Bulk purchase and sale Collection<ModelPlane> myPlanes = ... ; modelPlaneShop.buy(5, myPlanes); modelPlaneShop.sell(myPlanes);
Collection Subtyping Doesn’t Work! //  You can't buy a bunch of models from the train shop modelTrainShop.buy(5, myModelCollection); // Won't compile //  You can't sell a bunch of trains to the model shop modelShop.sell(myTrains); // Won't compile public interface Shop<T> { T buy(); void sell(T item); void buy(int numToBuy, Collection<T> myCollection); void sell(Collection<T> myLot); }
Bounded Wildcards to the Rescue public interface Shop<T> { T buy(); void sell(T item); void buy(int numToBuy, Collection <? super T>   myCollection); void sell(Collection <? extends T>  myLot); } // You can buy a bunch of models from the train shop modelTrainShop.buy(5, myModelCollection);   // Compiles // You can sell your train set to the model shop; modelShop.sell(myTrains);   // Compiles Because List<String> is a subtype of List<? extends Object> List<Object> is a supertype of List<? super String>
A Mnemonic for Wildcard Usage PECS  —  P roducer  e xtends,  C onsumer  s uper For a T producer, use Foo < ? extends T > For a T consumer, use Foo < ? super T >
PECS example: Stack Suppose you want to add bulk methods to  Stack<E> : void pushAll(Collection <E>  src); void popAll(Collection <E>  dst); - What we will get by PECS?
Applying PECS to  pushAll  methods void pushAll(Collection <? extends E > src); –  src  is an E producer void popAll(Collection <E>  dst);
Applying PECS to  popAll  methods void pushAll(Collection <? extends E>  src); –  src is an E producer void popAll(Collection <? super E >  dst); –  dst is an E consumer
What does it buy you? void pushAll(Collection<? extends E> src); void popAll(Collection<? super E> dst); - Caller can now  pushAll   from a  Collection<Long> or a  Collection<Number>   onto a  Stack<Number> - Caller can now  popAll   into a   Collection<Object> or a  Collection<Number>   from a   Stack<Number>
Advantages of generic type… Compile time error detection; more robust code Succinct and stylish coding practice. Less typing and repetition; adheres to DRY principle Reduce Accidental Complexity in your code. Flexibility of API design.
Under the hood Generic code translation :  By creating one unique byte code representation of each generic type (or method) and mapping all instantiations of the generic type (or method) to this unique representation. Type erasure :  A process that maps a parameterized type (or method) to its unique byte code representation by eliding type parameters and arguments .
code translation strategy Code specialization.  The compiler generates a new representation for every instantiation of a generic type or method. For instance, the compiler would generate code for a list of integers and additional, different code for a list of strings, a list of dates, a list of buffers, and so on.   Code sharing.   The compiler generates code for only one representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation, performing type checks and type conversions where needed. 
Generics is Evolution, Not Revolution Java Generics uses  Type erasure  and  non-Reification  technique
Steps of erasure and bridge method The steps performed during type erasure include:   Eliding type parameters.   When the compiler finds the definition of a generic type or method, it removes all occurrences of the type parameters and replaces them by their leftmost bound, or type Object if no bound had been specified.   Eliding type arguments.   When the compiler finds a parameterized type, i.e. an instantiation of a generic type, then it removes the type arguments. For instance, the types List<String> , Set<Long> , and Map<String,?> are translated to List , Set and Map respectively. 
Example (before type erasure) interface Comparable  <A>  {    public int compareTo(  A  that);  }  final class NumericValue implements Comparable  <NumericValue>  {    priva te byte value;     public  NumericValue (byte value) { this.value = value; }     public  byte getValue() { return value; }     public  int compareTo( NumericValue t hat) { return this.value - that.value; }  }  class Collections {     public static  <A extends Comparable<A>>A  max(Collection  <A>  xs) {      Iterator  <A>  xi = xs.iterator();      A w = xi.next();      while (xi.hasNext()) {        A x = xi.next();        if (w.compareTo(x) < 0) w = x;      }      return w;    }  }  final class Test {    public static void main (String[ ] args) {      LinkedList  <NumericValue>  numberList = new LinkedList  <NumericValue>  ();      numberList .add(new NumericValue((byte)0));       numberList .add(new NumericValue((byte)1));       NumericValue y = Collections.max( numberList );     }  } -  Type parameters are  green  and type arguments are  blue
Example (after type erasure) interface Comparable {    public int compareTo(  Object  that); }  final class NumericValue implements Comparable {  priva te byte value;    public  NumericValue (byte value) { this.value = value; }    public  byte getValue() { return value; }    public  int compareTo( NumericValue t hat)   { return this.value - that.value; }    public  int compareTo(Object that) { return this.compareTo((NumericValue)that);  }  }  class Collections {   public static  Comparable  max(Collection xs) {      Iterator xi = xs.iterator();       Comparable  w =  (Comparable)  xi.next();      while (xi.hasNext()) {         Comparable  x =  (Comparable)  xi.next();        if (w.compareTo(x) < 0) w = x;      }      return w;  }  }  final class Test {  public static void main (String[ ] args) {      LinkedList numberList = new LinkedList();      numberList .add(new NumericValue((byte)0));       numberList .add(new NumericValue((byte)1));       NumericValue y =  (NumericValue)  Collections.max( numberList );   }  } -  Bridge method  is generated by Compiler for NumericValue
Bridge method A synthetic method that the compiler generates in the course of type erasure.  It is sometimes needed when a type extends or implements a parameterized class or interface.   The compiler insert bridge methods in subtypes of parameterized supertypes to ensure that subtyping works as expected. Programmer cannot invoke bridge method. 
Converting Legacy code to generics Example of JDK API public static  <T  extends  Comparable<?  super  T>> T max(Collection<T> coll) This is fine, except that the erasure of this signature is public static  Comparable max(Collection coll) which is different than the original signature of max(): public static  Object max(Collection coll)
Conversion (contd..) Correct “max” for seamless running is legacy code: public static  <T  extends  Object & Comparable<?  super  T>> T max(Collection<?  extends  T> coll) Multiple bound/conjunctive bound systax: <T extends T1& T2 ... & Tn>
References Effective Java , 2 nd  edition  by Joshua Bloach. Java Generics and Collections  By Maurice Naftalin, Philip Wadler JavaOne technical sessions. http://www.generic-programming.org/ http://en.wikipedia.org/wiki/Generics_in_Java http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Q n A
Thank You

More Related Content

PDF
Generic programming
PDF
Generic Programming
PPTX
Generic Programming in java
PPTX
Java - Generic programming
PPTX
Modern C++
PDF
Regular types in C++
PPTX
Qcon2011 functions rockpresentation_scala
PDF
C++ Templates 2
Generic programming
Generic Programming
Generic Programming in java
Java - Generic programming
Modern C++
Regular types in C++
Qcon2011 functions rockpresentation_scala
C++ Templates 2

What's hot (20)

PPTX
Pointers Refrences & dynamic memory allocation in C++
PPT
Savitch ch 17
PPTX
Qcon2011 functions rockpresentation_f_sharp
PPT
Csharp In Detail Part2
PPT
Csharp4 operators and_casts
ODP
(2) c sharp introduction_basics_part_i
PPTX
C Programming Unit-2
PPT
C++ Interview Questions
PDF
C Programming - Refresher - Part II
PPT
C tutorial
PDF
Python Programming
PPTX
PPT
Practical Meta Programming
PDF
Introduction to C++
PPT
Jdk1.5 Features
PPTX
Operators in java
PDF
Intake 38 2
PPTX
C# in depth
Pointers Refrences & dynamic memory allocation in C++
Savitch ch 17
Qcon2011 functions rockpresentation_f_sharp
Csharp In Detail Part2
Csharp4 operators and_casts
(2) c sharp introduction_basics_part_i
C Programming Unit-2
C++ Interview Questions
C Programming - Refresher - Part II
C tutorial
Python Programming
Practical Meta Programming
Introduction to C++
Jdk1.5 Features
Operators in java
Intake 38 2
C# in depth
Ad

Similar to Generic Programming seminar (20)

PPT
Java Generics for Dummies
PDF
Generics Tutorial
PDF
117 A Outline 25
PPTX
PDF
Generics Tutorial
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
ODP
javasebeyondbasics
PPTX
Generic Collections and learn how to use it
PDF
Generics and collections in Java
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PPTX
Java generics final
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPT
Java Generics.ppt
PPT
Generics in java
PDF
Javase5generics
PPT
Generics Module 2Generics ModuleGenerics Module 2
PPT
Effective Java - Generics
ODP
Java 1.5 - whats new and modern patterns (2007)
PPT
Java Generics
Java Generics for Dummies
Generics Tutorial
117 A Outline 25
Generics Tutorial
Generic Types in Java (for ArtClub @ArtBrains Software)
javasebeyondbasics
Generic Collections and learn how to use it
Generics and collections in Java
Java Generics Introduction - Syntax Advantages and Pitfalls
Java generics final
Generics Module 2Generics Module Generics Module 2.pptx
Java Generics.ppt
Generics in java
Javase5generics
Generics Module 2Generics ModuleGenerics Module 2
Effective Java - Generics
Java 1.5 - whats new and modern patterns (2007)
Java Generics
Ad

Recently uploaded (20)

PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Approach and Philosophy of On baking technology
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Machine learning based COVID-19 study performance prediction
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PPTX
Spectroscopy.pptx food analysis technology
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
sap open course for s4hana steps from ECC to s4
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
KodekX | Application Modernization Development
PDF
Empathic Computing: Creating Shared Understanding
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Approach and Philosophy of On baking technology
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Machine learning based COVID-19 study performance prediction
Dropbox Q2 2025 Financial Results & Investor Presentation
MIND Revenue Release Quarter 2 2025 Press Release
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectroscopy.pptx food analysis technology
Chapter 3 Spatial Domain Image Processing.pdf
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
sap open course for s4hana steps from ECC to s4
20250228 LYD VKU AI Blended-Learning.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Agricultural_Statistics_at_a_Glance_2022_0.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
KodekX | Application Modernization Development
Empathic Computing: Creating Shared Understanding
Building Integrated photovoltaic BIPV_UPV.pdf
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing

Generic Programming seminar

  • 1. Generic Programming Seminar by Gautam Roy Debasish Sengupta <T> <E> <K, V>
  • 2. Today’s Agenda Theoretical concept of Generic Programming. Generics in Java. Questions are welcome throughout our session.
  • 3. What is Generic Programming? Raising the level of abstraction. What do we do when we program? We write a sequence of statements. What is the level of abstraction? We write at the level of source code. That gets translated directly into machine code, which is less abstract. <T> <E> <K, V>
  • 4. With generic programming, the level of abstraction is higher. The source code is just a pattern. The actual machine code that comes out depends on how the pattern is “filled-in”. static <T> List<T> newList() { return new ArrayList<T>(); } Without knowing T, no machine code can be generated from the above. Summary: With normal programming, we can know the overview of low level code generated from just by looking at the source. With generic programming, the code is at a higher level. Need to know other things, like the type parameters.
  • 5. So… Generic programming is programming that focuses on the algorithms and code at a higher level of abstraction that “normal” programming. Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters
  • 6. Path to Generic Programming Lifting : Lifting is the process of finding commonality among similar implementations of the same algorithm and then providing suitable abstractions so that a single, generic algorithm can cover many concrete implementations.
  • 7. Path to Generic Programming(contd..) Lifting is repeated until the generic algorithm has reached a suitable level of abstraction, where it provides maximal reusability while still yielding efficient implementations. The abstractions themselves are expressed as requirements on the parameters to the generic algorithm.
  • 8. By-product of Generic Programming Concept : A concept contains a set of requirements that describe a family of abstractions, typically data types. Examples of concepts include Iterator , Graph , Comparable etc.
  • 9. Format definition of Concept Once many algorithms within a given problem domain have been lifted, we start to see patterns among the requirements. It is common for the same set of requirements to be required by several different algorithms. When this occurs, each set of requirements is bundled into a concept .
  • 10. Thus, the output of the Generic Programming process is not just a generic, reusable implementation, but a better understanding of the problem domain.
  • 11. Lifting in Action Consider the following two definitions of “max”. int max(int a, int b) { if (a > b) return a; else return b; } float max(float a, float b) { if (a > b) return a; else return b; } How can we lift this to create just one version? <T> T max(T a, T b) { if (a > b) return a; else return b; } Does it compile in Java latest version?
  • 12. Evolution of Concept T needs to be Comparable so that we can compare various types. When we will write “max” for n number of elements then we need Container and also Comparable . - Here Comparable is a concept here.
  • 13. Lifted version of “max” <T extends Comparable<? super T>> T max(T a, T b) { Comparable c1 = (Comparable) a; Comparable c2 = (Comparable) b; if (c1.compareTo(c2) > 0) return a; else return b; } - This code introduce the concept Comparable.
  • 14. Generics and Polymorphism One view of polymorphism is Ability of code to work with different types Generic parameters and subtyping Both mechanisms for accomplishing polymorphism Both support programming by abstracting from concrete types Polymorphism using generic types - parametric polymorphism Polymorphism using subtypes - subtype polymorphism
  • 16. Original team behind Java Generics Left to right: Philip Wadler, Martin Odersky, Gilad Bracha, Dave Stoutamire Making Java easier to type, and easier to type
  • 17. Generics in Java Use of raw type in Java List l = new ArrayList(); // 1 l.add(Integer.valueOf(0)); // 2 Integer x = (Integer) l.get(0); // 3 - Can you see the disadvantages of these raw type?
  • 18. Use of generic type Same code with generics: List<Integer> l = new ArrayList<Integer>(); // 1 l.add(Integer.valueOf(0)); // 2 Integer x = l.get(0); // 3 And with Autoboxing and unboxing: List<Integer> l = new ArrayList<Integer>(); // 1 l.add(0); // 2 int x = l.get(0); // 3
  • 19. Advantages of generic type // Generic type: Good Collection<Coin> coinCollection = new ArrayList<Coin>(); coinCollection.add(new Stamp()); // Won’t compile ... for (Coin c : coinCollection) { ... } // Raw Type: Evil Collection coinCollection = new ArrayList(); coinCollection.add(new Stamp()); // Succeeds but should not ... for (Object o : coinCollection) { Coin c = (Coin) o; // Throws exception at runtime ... }
  • 20. Advantages of generic type ... Compile time error detection; more robust code Succinct and stylish coding practice. Less typing and repetition; adheres to DRY principle Reduce Accidental Complexity in code. Flexibility of API design.
  • 21. Generic Class and Constructor public class Pair<T, S> { private T first; private S second; public Pair(T f, S s) { first = f; second = s; } public T getFirst() { return first; } public S getSecond() { return second; } public String toString() { return &quot;(&quot; + first.toString() + &quot;, &quot; + second.toString() + &quot;)&quot;; } } - here T and S are type variable or formal type parameter
  • 22. Generic class in Action Pair<String, String> grade440 = new Pair<String, String>(&quot;mike&quot;, &quot;A&quot;); Pair<String, Integer> marks440 = new Pair<String, Integer>(&quot;mike&quot;, 100); System.out.println(&quot;grade:&quot; + grade440.toString()); System.out.println(&quot;marks:&quot; + marks440.toString());
  • 23. Generic interface Same as generic class public interface List<E> { void add(E x); Iterator<E> iterator(); } public interface Iterator<E> { E next(); boolean hasNext(); } Lots of example in Java collection framework like List, Set, Map etc.
  • 24. Type inference The automatic deduction of the type arguments of a generic method at compile time. List<T> l = new ArrayList<T>(); Does it compile in Java latest version? public static <T> newList() { return new ArrayList<T>; } Does it compile in Java latest version?
  • 25. Generic Methods A generic method can be invoked in two ways: Explicit type argument specification .  The type arguments are explicitly specified in a type argument list. Automatic type argument inference. The method is invoked like regular non-generic methods, that is, without specification of the type arguments.  In this case the compiler automatically infers the type arguments from the invocation context.   public <T> Pair<T,T> twice(T value) { return new Pair<T,T>(value, value); }
  • 26. Generic method in Action Explicit type argument: Pair<String, String> pair = this. <String> twice(&quot;Hello&quot;); Or using type inference Pair<String, String> pair = twice (&quot;Hello&quot;); Explicit type argument System.out.println(Utilities. <String> max(&quot;abc&quot;,&quot;xyz&quot;)); Or using type inference System.out.println(Utilities. max (&quot;abc&quot;,&quot;xyz&quot;));
  • 27. Type parameter naming conventions E - Element (used extensively by the Java Collections Framework) K - Key N - Number T - Type V - Value S,U,V etc. - 2nd, 3rd, 4th types
  • 28. Generics and Wildcards The method prints out all the elements in a collection: void printCollection(Collection c) { Iterator i = c.iterator(); for (k = 0; k < c.size(); k++) { System.out.println(i.next()); } } One naive attempt at writing it using generics: void printCollection(Collection<Object> c) { for (Object e : c) { System.out.println(e); } } - Why it is inflexible?
  • 29. Generics and Subtyping Arrays are covariant but generic types are contravariant. That is, List<String> is not a subtype of List<Object> Good for compile-time type safety, but inflexible Wildcard and bounded wildcard to the rescue
  • 30. Wildcards to the rescue Correct method void printCollection(Collection<?> c) { for (Object e : c) { System.out.println(e); } } ? is wildcard type here . But what about this? Collection<?> c = new ArrayList<String>(); c.add(new Object());
  • 31. Example of Subtyping public interface Shop<T> { T buy(); void sell(T myItem); void buy(int numToBuy, Collection<T> myCollection); void sell(Collection<T> myLot); } class Model { } class ModelPlane extends Model { } class ModelTrain extends Model { }
  • 32. Works Fine If You Stick to One Type // Individual purchase and sale Shop<ModelPlane> modelPlaneShop = ... ; ModelPlane myPlane = modelPlaneShop.buy(); modelPlaneShop.sell(myPlane); // Bulk purchase and sale Collection<ModelPlane> myPlanes = ... ; modelPlaneShop.buy(5, myPlanes); modelPlaneShop.sell(myPlanes);
  • 33. Collection Subtyping Doesn’t Work! // You can't buy a bunch of models from the train shop modelTrainShop.buy(5, myModelCollection); // Won't compile // You can't sell a bunch of trains to the model shop modelShop.sell(myTrains); // Won't compile public interface Shop<T> { T buy(); void sell(T item); void buy(int numToBuy, Collection<T> myCollection); void sell(Collection<T> myLot); }
  • 34. Bounded Wildcards to the Rescue public interface Shop<T> { T buy(); void sell(T item); void buy(int numToBuy, Collection <? super T> myCollection); void sell(Collection <? extends T> myLot); } // You can buy a bunch of models from the train shop modelTrainShop.buy(5, myModelCollection); // Compiles // You can sell your train set to the model shop; modelShop.sell(myTrains); // Compiles Because List<String> is a subtype of List<? extends Object> List<Object> is a supertype of List<? super String>
  • 35. A Mnemonic for Wildcard Usage PECS — P roducer e xtends, C onsumer s uper For a T producer, use Foo < ? extends T > For a T consumer, use Foo < ? super T >
  • 36. PECS example: Stack Suppose you want to add bulk methods to Stack<E> : void pushAll(Collection <E> src); void popAll(Collection <E> dst); - What we will get by PECS?
  • 37. Applying PECS to pushAll methods void pushAll(Collection <? extends E > src); – src is an E producer void popAll(Collection <E> dst);
  • 38. Applying PECS to popAll methods void pushAll(Collection <? extends E> src); – src is an E producer void popAll(Collection <? super E > dst); – dst is an E consumer
  • 39. What does it buy you? void pushAll(Collection<? extends E> src); void popAll(Collection<? super E> dst); - Caller can now pushAll from a Collection<Long> or a Collection<Number> onto a Stack<Number> - Caller can now popAll into a Collection<Object> or a Collection<Number> from a Stack<Number>
  • 40. Advantages of generic type… Compile time error detection; more robust code Succinct and stylish coding practice. Less typing and repetition; adheres to DRY principle Reduce Accidental Complexity in your code. Flexibility of API design.
  • 41. Under the hood Generic code translation : By creating one unique byte code representation of each generic type (or method) and mapping all instantiations of the generic type (or method) to this unique representation. Type erasure : A process that maps a parameterized type (or method) to its unique byte code representation by eliding type parameters and arguments .
  • 42. code translation strategy Code specialization. The compiler generates a new representation for every instantiation of a generic type or method. For instance, the compiler would generate code for a list of integers and additional, different code for a list of strings, a list of dates, a list of buffers, and so on.   Code sharing. The compiler generates code for only one representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation, performing type checks and type conversions where needed. 
  • 43. Generics is Evolution, Not Revolution Java Generics uses Type erasure and non-Reification technique
  • 44. Steps of erasure and bridge method The steps performed during type erasure include:  Eliding type parameters. When the compiler finds the definition of a generic type or method, it removes all occurrences of the type parameters and replaces them by their leftmost bound, or type Object if no bound had been specified.  Eliding type arguments. When the compiler finds a parameterized type, i.e. an instantiation of a generic type, then it removes the type arguments. For instance, the types List<String> , Set<Long> , and Map<String,?> are translated to List , Set and Map respectively. 
  • 45. Example (before type erasure) interface Comparable <A> {   public int compareTo( A that); } final class NumericValue implements Comparable <NumericValue> {   priva te byte value;    public  NumericValue (byte value) { this.value = value; }    public  byte getValue() { return value; }    public  int compareTo( NumericValue t hat) { return this.value - that.value; } } class Collections {    public static <A extends Comparable<A>>A max(Collection <A> xs) {     Iterator <A> xi = xs.iterator();     A w = xi.next();     while (xi.hasNext()) {       A x = xi.next();       if (w.compareTo(x) < 0) w = x;     }     return w;   } } final class Test {   public static void main (String[ ] args) {     LinkedList <NumericValue> numberList = new LinkedList <NumericValue> ();     numberList .add(new NumericValue((byte)0));      numberList .add(new NumericValue((byte)1));      NumericValue y = Collections.max( numberList );    } } - Type parameters are green and type arguments are blue
  • 46. Example (after type erasure) interface Comparable {   public int compareTo( Object that); } final class NumericValue implements Comparable { priva te byte value;   public  NumericValue (byte value) { this.value = value; }   public  byte getValue() { return value; }   public  int compareTo( NumericValue t hat)   { return this.value - that.value; }   public  int compareTo(Object that) { return this.compareTo((NumericValue)that);  } } class Collections {  public static Comparable max(Collection xs) {     Iterator xi = xs.iterator();     Comparable w = (Comparable) xi.next();     while (xi.hasNext()) {       Comparable x = (Comparable) xi.next();       if (w.compareTo(x) < 0) w = x;     }     return w; } } final class Test { public static void main (String[ ] args) {     LinkedList numberList = new LinkedList();     numberList .add(new NumericValue((byte)0));      numberList .add(new NumericValue((byte)1));      NumericValue y = (NumericValue) Collections.max( numberList );  } } - Bridge method is generated by Compiler for NumericValue
  • 47. Bridge method A synthetic method that the compiler generates in the course of type erasure.  It is sometimes needed when a type extends or implements a parameterized class or interface. The compiler insert bridge methods in subtypes of parameterized supertypes to ensure that subtyping works as expected. Programmer cannot invoke bridge method. 
  • 48. Converting Legacy code to generics Example of JDK API public static <T extends Comparable<? super T>> T max(Collection<T> coll) This is fine, except that the erasure of this signature is public static Comparable max(Collection coll) which is different than the original signature of max(): public static Object max(Collection coll)
  • 49. Conversion (contd..) Correct “max” for seamless running is legacy code: public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) Multiple bound/conjunctive bound systax: <T extends T1& T2 ... & Tn>
  • 50. References Effective Java , 2 nd edition by Joshua Bloach. Java Generics and Collections By Maurice Naftalin, Philip Wadler JavaOne technical sessions. http://www.generic-programming.org/ http://en.wikipedia.org/wiki/Generics_in_Java http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
  • 51. Q n A