SlideShare a Scribd company logo
1 of 14
Generic Programming In Java
DESIGND BY GARIK KALASHYAN
Why Generic Programming
 Generic programming means writing code that can be reused for objects of many
different types.
 For example, you don’t want to program separate classes to collect String and File
objects. And you don’t have to—the single class ArrayList collects objects of any
class. This is one example of generic programming.
Defining a Simple Generic Class
public class SomeClass<T>
{
private T someProperty;
public SomeClass() { someProperty = null;}
public SomeClass(T someProperty) { this. someProperty = someProperty;}
public T getSomeProperty() { return someProperty; }
public void setSomeProperty(T newValue) {someProperty = newValue; }
}
USAGE: SomeClass<String>
public class MyEntry<T,U>
{
private T key;
private U value;
public MyEntry() { key = null; value = null; }
public MyEntry(T key, U value) { this.key = key; this.value = value; }
public T getKey() { return key; }
public U getValue() { return value; }
public void setKey(T newKey) { key = newKey; }
public void setValue(U newValue) { value = newValue; }
}
USAGE: MyEntry<String,Integer>
Generic Methods
 We can also define a single method with type parameters.
 Example:
class ArrayAlg {
public static <T> T getMiddle(T... a) {
return a[a.length / 2];
}
}
USAGES:
ArrayAlg.<String>getMiddle("John", "Q.", "Public");
ArrayAlg.getMiddle("John", "Q.", "Public");
ArrayAlg.getMiddle(3.14, 1729, 0);
Smart Java 
 C++ NOTE: In C++, you place the type parameters after the method name. That
can lead to nasty parsing ambiguities. For example, g(f<a,b>(c)) can mean “call g
with the result of f<a,b>(c)”, or “call g with the two boolean values f<a and b>(c)”.
Bounds for Type Variables
 Sometimes, a class or a method needs to place restrictions on type variables.
 For example we want to find the minimum element of an array but we are passing
not comparable types into generic, for this case there is bounding for types.
Example: <T extends BoundingType>
Notice: here we have keyword extends instead of implements for interfaces
Bounds for Type Variables
 A type variable or wildcard can have multiple bounds.
Example: T extends Comparable & Serializable
 The bounding types are separated by ampersands (&) because commas are used to separate type
variables.
 As with Java inheritance, you can have as many interface supertypes as you like,but at most one of the
bounds can be a class. If you have a class as a bound, it must be the first one in the bounds list.
QUESTIONS ?
Processes in Virtual Machine
• TYPE ERASURE
• TRANSLATING GENERIC METHODS
• CALLING LEGACY CODE
Type Erasure
Whenever you define a generic
type, a corresponding raw type is
automatically provided. The
name of the raw type is simply
the name of the generic type,
with the type parameters
removed. The type variables are
erased and replaced by their
bounding types (or Object for
variables without bounds).
Replace all type parameters in generic types with their bounds
or Object if the type parameters are unbounded. The produced
bytecode, therefore, contains only ordinary classes, interfaces, and
methods.
Insert type casts if necessary to preserve type safety.
Generate bridge methods to preserve polymorphism in extended
generic types.
Type erasure ensures that no new classes are
for parameterized types; consequently, generics
no runtime overhead.
Translating
Generic
Methods  Type erasure also happens for generic
methods. Programmers usually think of a
generic method such as
public static <T extends Comparable> T min(T[]
a)
as a whole family of methods, but after erasure,
only a single method is left:
public static Comparable min(Comparable[] a)
 Note that the type parameter T has been
erased, leaving only its bounding type
Comparable. Erasure of methods brings up a
couple of complexities.
Bridge Methods
Covariant return types
In summary about translation
of Java
 There are no generics in the virtual machine, only ordinary classes and methods.
 All type parameters are replaced by their bounds.
 Bridge methods are synthesized to preserve polymorphism.
 Casts are inserted as necessary to preserve type safety.
Calling Legacy
Code
void
setLabelTable(Dictionar
y table)
slider.setLabelTabl
e(labelTable); //
Warning
@SuppressWarnings("u
nchecked")
Dictionary<Integer,
Components>
labelTable =
slider.getLabelTable(); //
No warning
Dictionary<Integer,
Components>
labelTable =
slider.getLabelTable();
// Warning
When we use generic
without raw type. It is need
when we have code in which
somewhere isn’t supported
new implementation of
generics . So we receive
warning from compiler.
Restrictions and Limitations
• TYPE PARAMETERS CANNOT BE INSTANTIATED WITH PRIMITIVE TYPES
• RUNTIME TYPE INQUIRY ONLY WORKS WITH RAW TYPES
• YOU CANNOT CREATE ARRAYS OF PARAMETERIZED TYPES
• VARARGS WARNINGS
• YOU CANNOT INSTANTIATE TYPE VARIABLES
• YOU CANNOT CONSTRUCT A GENERIC ARRAY
• TYPE VARIABLES ARE NOT VALID IN STATIC CONTEXTS OF GENERIC CLASSES
• YOU CANNOT THROW OR CATCH INSTANCES OF A GENERIC CLASS
• YOU CAN DEFEAT CHECKED EXCEPTION CHECKING
• BEWARE OF CLASHES AFTER ERASURE

More Related Content

What's hot

Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and StringsEduardo Bergavera
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
Java Generics
Java GenericsJava Generics
Java Genericsjeslie
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaEduardo Bergavera
 
Core java concepts
Core java concepts Core java concepts
Core java concepts javeed_mhd
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywordsmanish kumar
 
Java basics variables
 Java basics   variables Java basics   variables
Java basics variablesJoeReddieMedia
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentalsHCMUTE
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stalMichael Stal
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptmanish kumar
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelRamrao Desai
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaMichael Stal
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 

What's hot (20)

Chapter 9 - Characters and Strings
Chapter 9 - Characters and StringsChapter 9 - Characters and Strings
Chapter 9 - Characters and Strings
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Java Generics
Java GenericsJava Generics
Java Generics
 
M C6java3
M C6java3M C6java3
M C6java3
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
Core java concepts
Core java concepts Core java concepts
Core java concepts
 
Lecture 4_Java Method-constructor_imp_keywords
Lecture   4_Java Method-constructor_imp_keywordsLecture   4_Java Method-constructor_imp_keywords
Lecture 4_Java Method-constructor_imp_keywords
 
Java basics variables
 Java basics   variables Java basics   variables
Java basics variables
 
Java fundamentals
Java fundamentalsJava fundamentals
Java fundamentals
 
Oop2011 actor presentation_stal
Oop2011 actor presentation_stalOop2011 actor presentation_stal
Oop2011 actor presentation_stal
 
Lecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops conceptLecture - 3 Variables-data type_operators_oops concept
Lecture - 3 Variables-data type_operators_oops concept
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Unit 1 Java
Unit 1 JavaUnit 1 Java
Unit 1 Java
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
M C6java2
M C6java2M C6java2
M C6java2
 
Qcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scalaQcon2011 functions rockpresentation_scala
Qcon2011 functions rockpresentation_scala
 
Java generics
Java genericsJava generics
Java generics
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Object-Oriented Programming Using C++
Object-Oriented Programming Using C++Object-Oriented Programming Using C++
Object-Oriented Programming Using C++
 

Similar to Generic Programming in java (20)

Generics
GenericsGenerics
Generics
 
Generics C#
Generics C#Generics C#
Generics C#
 
Types, classes and concepts
Types, classes and conceptsTypes, classes and concepts
Types, classes and concepts
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Types in Java (for ArtClub @ArtBrains Software)
 
Generics
GenericsGenerics
Generics
 
More Little Wonders of C#/.NET
More Little Wonders of C#/.NETMore Little Wonders of C#/.NET
More Little Wonders of C#/.NET
 
Generics
GenericsGenerics
Generics
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Introduction to new features in java 8
Introduction to new features in java 8Introduction to new features in java 8
Introduction to new features in java 8
 
Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
 
Templates
TemplatesTemplates
Templates
 
Savitch Ch 17
Savitch Ch 17Savitch Ch 17
Savitch Ch 17
 
C++ Templates 2
C++ Templates 2C++ Templates 2
C++ Templates 2
 
Annotations
AnnotationsAnnotations
Annotations
 
Evolution of c# - by K.Jegan
Evolution of c# - by K.JeganEvolution of c# - by K.Jegan
Evolution of c# - by K.Jegan
 
OOP - Templates
OOP - TemplatesOOP - Templates
OOP - Templates
 
Swift Generics
Swift GenericsSwift Generics
Swift Generics
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
 
Notes(1).pptx
Notes(1).pptxNotes(1).pptx
Notes(1).pptx
 
Java generics final
Java generics finalJava generics final
Java generics final
 

Recently uploaded

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 

Recently uploaded (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

Generic Programming in java

  • 1. Generic Programming In Java DESIGND BY GARIK KALASHYAN
  • 2. Why Generic Programming  Generic programming means writing code that can be reused for objects of many different types.  For example, you don’t want to program separate classes to collect String and File objects. And you don’t have to—the single class ArrayList collects objects of any class. This is one example of generic programming.
  • 3. Defining a Simple Generic Class public class SomeClass<T> { private T someProperty; public SomeClass() { someProperty = null;} public SomeClass(T someProperty) { this. someProperty = someProperty;} public T getSomeProperty() { return someProperty; } public void setSomeProperty(T newValue) {someProperty = newValue; } } USAGE: SomeClass<String> public class MyEntry<T,U> { private T key; private U value; public MyEntry() { key = null; value = null; } public MyEntry(T key, U value) { this.key = key; this.value = value; } public T getKey() { return key; } public U getValue() { return value; } public void setKey(T newKey) { key = newKey; } public void setValue(U newValue) { value = newValue; } } USAGE: MyEntry<String,Integer>
  • 4. Generic Methods  We can also define a single method with type parameters.  Example: class ArrayAlg { public static <T> T getMiddle(T... a) { return a[a.length / 2]; } } USAGES: ArrayAlg.<String>getMiddle("John", "Q.", "Public"); ArrayAlg.getMiddle("John", "Q.", "Public"); ArrayAlg.getMiddle(3.14, 1729, 0);
  • 5. Smart Java   C++ NOTE: In C++, you place the type parameters after the method name. That can lead to nasty parsing ambiguities. For example, g(f<a,b>(c)) can mean “call g with the result of f<a,b>(c)”, or “call g with the two boolean values f<a and b>(c)”.
  • 6. Bounds for Type Variables  Sometimes, a class or a method needs to place restrictions on type variables.  For example we want to find the minimum element of an array but we are passing not comparable types into generic, for this case there is bounding for types. Example: <T extends BoundingType> Notice: here we have keyword extends instead of implements for interfaces
  • 7. Bounds for Type Variables  A type variable or wildcard can have multiple bounds. Example: T extends Comparable & Serializable  The bounding types are separated by ampersands (&) because commas are used to separate type variables.  As with Java inheritance, you can have as many interface supertypes as you like,but at most one of the bounds can be a class. If you have a class as a bound, it must be the first one in the bounds list.
  • 9. Processes in Virtual Machine • TYPE ERASURE • TRANSLATING GENERIC METHODS • CALLING LEGACY CODE
  • 10. Type Erasure Whenever you define a generic type, a corresponding raw type is automatically provided. The name of the raw type is simply the name of the generic type, with the type parameters removed. The type variables are erased and replaced by their bounding types (or Object for variables without bounds). Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded. The produced bytecode, therefore, contains only ordinary classes, interfaces, and methods. Insert type casts if necessary to preserve type safety. Generate bridge methods to preserve polymorphism in extended generic types. Type erasure ensures that no new classes are for parameterized types; consequently, generics no runtime overhead.
  • 11. Translating Generic Methods  Type erasure also happens for generic methods. Programmers usually think of a generic method such as public static <T extends Comparable> T min(T[] a) as a whole family of methods, but after erasure, only a single method is left: public static Comparable min(Comparable[] a)  Note that the type parameter T has been erased, leaving only its bounding type Comparable. Erasure of methods brings up a couple of complexities. Bridge Methods Covariant return types
  • 12. In summary about translation of Java  There are no generics in the virtual machine, only ordinary classes and methods.  All type parameters are replaced by their bounds.  Bridge methods are synthesized to preserve polymorphism.  Casts are inserted as necessary to preserve type safety.
  • 13. Calling Legacy Code void setLabelTable(Dictionar y table) slider.setLabelTabl e(labelTable); // Warning @SuppressWarnings("u nchecked") Dictionary<Integer, Components> labelTable = slider.getLabelTable(); // No warning Dictionary<Integer, Components> labelTable = slider.getLabelTable(); // Warning When we use generic without raw type. It is need when we have code in which somewhere isn’t supported new implementation of generics . So we receive warning from compiler.
  • 14. Restrictions and Limitations • TYPE PARAMETERS CANNOT BE INSTANTIATED WITH PRIMITIVE TYPES • RUNTIME TYPE INQUIRY ONLY WORKS WITH RAW TYPES • YOU CANNOT CREATE ARRAYS OF PARAMETERIZED TYPES • VARARGS WARNINGS • YOU CANNOT INSTANTIATE TYPE VARIABLES • YOU CANNOT CONSTRUCT A GENERIC ARRAY • TYPE VARIABLES ARE NOT VALID IN STATIC CONTEXTS OF GENERIC CLASSES • YOU CANNOT THROW OR CATCH INSTANCES OF A GENERIC CLASS • YOU CAN DEFEAT CHECKED EXCEPTION CHECKING • BEWARE OF CLASHES AFTER ERASURE