SlideShare a Scribd company logo
1 of 24
Java Generics
(Under The Hood Of The Compiler)
By: Harmeet Singh (Taara)
(Java EE Developer)
harmeetsingh.0013@gmail.com
http://harmeetsingh13.blogspot.in
skype: harmeetsingh0013
Contact: Via mail or Skype
Contents
1. Generic Type.
2. WildCards in Generics.
3. Unchecked Warnings.
4. Heap Pollution.
5. Type Eraser.
6. Bridge method.
7. Type Erasure of A Parameterized Type.
8. Type Erasure of A Type Parameter.
9. Type Erasure of A Generic Method.
10.Reficiation.
11.Reifilable Type.
Acknowledgement
● Special Thanks to “Angelika Langer” (Trainer & Author
and Mentor). Everything about generics in this
presentation is get from “Angelika Langer” Generics
FAQ.
info@angelikaLanger.com
Generic Type
● Type Parameter: Is a placeholder that will later be replace but a type
argument.
● A parameterized or generic type is an instantiation of a generic type with
actual argument.
● Define Generics:
class Pair<S,T>{
private S first;
private T second;
-----------------
}
Generic Type
● Types that cannot have type parameter :
o Anonymous Inner Classes
o Exception Types
o Enum Types.
● Generic Type Instantiated:
o Pair<String, Long> pair = new Pair<String, Long>();
● Generics Declarations:
o Collection<String> : Concrete Declaration.
o Collection<?> : Wild Card Declaration.
WildCard in Generics
● We are not create directly object whose types is wildcard parameterized
object
ArrayList<?> list = new ArrayList<?>(); //error
● WildCard parameterized type is not declare in a supertype
class WildCardParam<?>{ //error
---------------------
}
WildCards In Generics
● WildCard Types Family:
o “ ? “ : Unbounded WildCard
o “ ? extends Type ” : WildCard With an upper bound
o “ ? super Type “ : WildCard With an lower bound
WildCards in Generics
● WildCards Bounds: A Reference type that is used to further describe the
family of types denoted by a wildcard.
● Difference between WildCard Bound and Type Parameter Bound:
o A WildCard can have only one bound, while a type parameter can
have several bounds.
o A WildCard can have lower or an upper bound, while there is no such
things as a lower bound for a types parameter.
WildCards In Generics
● Does “extends” always means Inheritance ? : extends is an overloaded
keyword in java. it has different meanings, depending on the context it
appears. The extends keyword appear in four different locations :
o In the Definition of Class.
o In the Definition of Interface.
o In the Definition of Type Parameter bounds.
o In the Definition of WildCards Bounds.
Unchecked Warnings
● Compiler and the runtime system do not have enough type information to
perform all type checks that would be necessary to ensure type safety.
example:
TreeSet set = new TreeSet();
set.add(“abc”); //unchecked warnings.
● Xlint:unchecked enable “unchecked” warnings.
● Xlint:-unchecked and @SuppressWarnings(“unchecked”) disable
“unchecked” warnings.
Heap Pollution
● A Situation where a variable of parameterized types refer to an Object that
is not of that parameterized type.
● Reason of Heap Pollution Occur :-
1. Mixing Raw and Parameterized Type.
2. Unwise Casting.
3. Separate Compilation.
Type Erasure
● How Compiler Translate Java Generics:
○ Compiler translate generic type or method(in any language, not just
java) has in principle two choice.
■ Code Specialization : The compiler generates a new
representation of a generic type of method.
■ 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 of method to the unique
representation , perform type check and type conversion where
needed.
Type Erasure
● What is Type Erasure ?
o The compiler generates only one byte code representation of a
generic type or method and maps all the instantiations of the generic
type or method to the unique representation.
● The type Erasure process can be imagined as a translation from generic
Java Source code back into regular Java Code.
● The Steps performed during type erasure :
o Eliding Type Parameter : 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, or type Object if no
bounds specified. Ex: <T> var; into Object var;
Type Erasure
● The Steps performed during type erasure :
o Eliding Type argument: When the compiler finds a parameterized
type, i.e an instantiation of a generic types, then it removes the type
arguments. Like : List<String>, Set<Long> and Map<String, ?> are
translated to List, Set and Map respectively.
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.
Example Before type Erasure:
Bridge Method
Example After type Erasure:
● Side Effect of type erasure is that two methods have identical signature
before type erasure and different signature after type erasure.
Bridge Method
● Under which circumstances is a bridge method generated ?
o Bridge methods are necessary when a class implements a parameterized interface or
extends a parametrized superclass and type erasure changes the arguments type of any
of the inherited non-static method.
Bridge Method
● The compiler must add the bridge methods even if the subclass does not
override the inherited method.
Type Erasure OF Parameterized Type
● The Erasure of a parameterized type is the type without any type argument
(i.e the raw type). The definition extends to arrays and nested types.
Type Erasure Of Type Parameter
● The type erasure of a type parameter is the erasure of its leftmost bound.
The type erasure of an unbounded type parameter is type Object.
Examples :
Type Erasure Of Generic Type
● The Erasure of a method signature consisting of the same name and the
erasures of all the formal method parameters types.
Examples :
Reficiation
● Representing type parameters and arguments of generic types and
method at runtime. Reficiation is the opposite of type Erasure.
Reifiable
● A type whose type information is fully available at run time, that is, a type that does not lose
information in the course of type erasure.
● The following types are reifiable:
o primitive types
o non-generic (or non-parameterized) reference types
o unbounded wildcard instantiations
o raw types
o arrays of any of the above
● The non-reifiable types, which lose type information as a side effect of type erasure, are:
o instantiations of a generic type with at least one concrete type argument
o instantiations of a generic type with at least one bounded wildcard as type argument
● Reifiable types are permitted in some places where non-reifiable types are disallowed.
o as type in an instanceof expression
o as component type of an array
References
● http://www.angelikalanger.com/GenericsFA
Q/JavaGenericsFAQ.html

More Related Content

What's hot

What's hot (20)

Java logging
Java loggingJava logging
Java logging
 
C# Generics
C# GenericsC# Generics
C# Generics
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
AngularJS - Services
AngularJS - ServicesAngularJS - Services
AngularJS - Services
 
Java reflection
Java reflectionJava reflection
Java reflection
 
Java Introduction
Java IntroductionJava Introduction
Java Introduction
 
Java8 features
Java8 featuresJava8 features
Java8 features
 
Core Java
Core JavaCore Java
Core Java
 
Abstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and InterfacesAbstraction in java [abstract classes and Interfaces
Abstraction in java [abstract classes and Interfaces
 
Spring boot
Spring bootSpring boot
Spring boot
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
Java 8 streams
Java 8 streamsJava 8 streams
Java 8 streams
 
Java Spring
Java SpringJava Spring
Java Spring
 
JCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTSJCConf 2021 - Java17: The Next LTS
JCConf 2021 - Java17: The Next LTS
 
Java: Classes Abstratas, Anônimas, Interface
Java: Classes Abstratas, Anônimas, InterfaceJava: Classes Abstratas, Anônimas, Interface
Java: Classes Abstratas, Anônimas, Interface
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
JavaScript for ABAP Programmers - 3/7 Syntax
JavaScript for ABAP Programmers - 3/7 SyntaxJavaScript for ABAP Programmers - 3/7 Syntax
JavaScript for ABAP Programmers - 3/7 Syntax
 
Java class,object,method introduction
Java class,object,method introductionJava class,object,method introduction
Java class,object,method introduction
 

Viewers also liked

Viewers also liked (10)

Lambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian GoetzLambda: A Peek Under The Hood - Brian Goetz
Lambda: A Peek Under The Hood - Brian Goetz
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
Cracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 ExamsCracking OCA and OCP Java 8 Exams
Cracking OCA and OCP Java 8 Exams
 
The Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFuturesThe Future of Futures - A Talk About Java 8 CompletableFutures
The Future of Futures - A Talk About Java 8 CompletableFutures
 
Asynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFutureAsynchronous API in Java8, how to use CompletableFuture
Asynchronous API in Java8, how to use CompletableFuture
 
The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8The Dark Side Of Lambda Expressions in Java 8
The Dark Side Of Lambda Expressions in Java 8
 
Advanced Production Debugging
Advanced Production DebuggingAdvanced Production Debugging
Advanced Production Debugging
 
Scalability, Availability & Stability Patterns
Scalability, Availability & Stability PatternsScalability, Availability & Stability Patterns
Scalability, Availability & Stability Patterns
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
From Microliths To Microsystems
From Microliths To MicrosystemsFrom Microliths To Microsystems
From Microliths To Microsystems
 

Similar to Java generics(Under The Hood Of The Compiler) by Harmeet singh

Similar to Java generics(Under The Hood Of The Compiler) by Harmeet singh (20)

Typescript: Beginner to Advanced
Typescript: Beginner to AdvancedTypescript: Beginner to Advanced
Typescript: Beginner to Advanced
 
Generic Programming in java
Generic Programming in javaGeneric Programming in java
Generic Programming in java
 
2._Java_Syntax_and_Data_Type.pptx.pdf
2._Java_Syntax_and_Data_Type.pptx.pdf2._Java_Syntax_and_Data_Type.pptx.pdf
2._Java_Syntax_and_Data_Type.pptx.pdf
 
Generics
GenericsGenerics
Generics
 
Type Systems
Type SystemsType Systems
Type Systems
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Generics
GenericsGenerics
Generics
 
Java - Generic programming
Java - Generic programmingJava - Generic programming
Java - Generic programming
 
.Net F# Generic class
.Net F# Generic class.Net F# Generic class
.Net F# Generic class
 
Language tour of dart
Language tour of dartLanguage tour of dart
Language tour of dart
 
Introduction To C#
Introduction To C#Introduction To C#
Introduction To C#
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
Type system
Type systemType system
Type system
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Full CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java languageFull CSE 310 Unit 1 PPT.pptx for java language
Full CSE 310 Unit 1 PPT.pptx for java language
 
Lecture02 java
Lecture02 javaLecture02 java
Lecture02 java
 
TypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript applicationTypeScript introduction to scalable javascript application
TypeScript introduction to scalable javascript application
 
C# - Igor Ralić
C# - Igor RalićC# - Igor Ralić
C# - Igor Ralić
 
Generics
GenericsGenerics
Generics
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 

Java generics(Under The Hood Of The Compiler) by Harmeet singh

  • 1. Java Generics (Under The Hood Of The Compiler) By: Harmeet Singh (Taara) (Java EE Developer) harmeetsingh.0013@gmail.com http://harmeetsingh13.blogspot.in skype: harmeetsingh0013 Contact: Via mail or Skype
  • 2. Contents 1. Generic Type. 2. WildCards in Generics. 3. Unchecked Warnings. 4. Heap Pollution. 5. Type Eraser. 6. Bridge method. 7. Type Erasure of A Parameterized Type. 8. Type Erasure of A Type Parameter. 9. Type Erasure of A Generic Method. 10.Reficiation. 11.Reifilable Type.
  • 3. Acknowledgement ● Special Thanks to “Angelika Langer” (Trainer & Author and Mentor). Everything about generics in this presentation is get from “Angelika Langer” Generics FAQ. info@angelikaLanger.com
  • 4. Generic Type ● Type Parameter: Is a placeholder that will later be replace but a type argument. ● A parameterized or generic type is an instantiation of a generic type with actual argument. ● Define Generics: class Pair<S,T>{ private S first; private T second; ----------------- }
  • 5. Generic Type ● Types that cannot have type parameter : o Anonymous Inner Classes o Exception Types o Enum Types. ● Generic Type Instantiated: o Pair<String, Long> pair = new Pair<String, Long>(); ● Generics Declarations: o Collection<String> : Concrete Declaration. o Collection<?> : Wild Card Declaration.
  • 6. WildCard in Generics ● We are not create directly object whose types is wildcard parameterized object ArrayList<?> list = new ArrayList<?>(); //error ● WildCard parameterized type is not declare in a supertype class WildCardParam<?>{ //error --------------------- }
  • 7. WildCards In Generics ● WildCard Types Family: o “ ? “ : Unbounded WildCard o “ ? extends Type ” : WildCard With an upper bound o “ ? super Type “ : WildCard With an lower bound
  • 8. WildCards in Generics ● WildCards Bounds: A Reference type that is used to further describe the family of types denoted by a wildcard. ● Difference between WildCard Bound and Type Parameter Bound: o A WildCard can have only one bound, while a type parameter can have several bounds. o A WildCard can have lower or an upper bound, while there is no such things as a lower bound for a types parameter.
  • 9. WildCards In Generics ● Does “extends” always means Inheritance ? : extends is an overloaded keyword in java. it has different meanings, depending on the context it appears. The extends keyword appear in four different locations : o In the Definition of Class. o In the Definition of Interface. o In the Definition of Type Parameter bounds. o In the Definition of WildCards Bounds.
  • 10. Unchecked Warnings ● Compiler and the runtime system do not have enough type information to perform all type checks that would be necessary to ensure type safety. example: TreeSet set = new TreeSet(); set.add(“abc”); //unchecked warnings. ● Xlint:unchecked enable “unchecked” warnings. ● Xlint:-unchecked and @SuppressWarnings(“unchecked”) disable “unchecked” warnings.
  • 11. Heap Pollution ● A Situation where a variable of parameterized types refer to an Object that is not of that parameterized type. ● Reason of Heap Pollution Occur :- 1. Mixing Raw and Parameterized Type. 2. Unwise Casting. 3. Separate Compilation.
  • 12. Type Erasure ● How Compiler Translate Java Generics: ○ Compiler translate generic type or method(in any language, not just java) has in principle two choice. ■ Code Specialization : The compiler generates a new representation of a generic type of method. ■ 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 of method to the unique representation , perform type check and type conversion where needed.
  • 13. Type Erasure ● What is Type Erasure ? o The compiler generates only one byte code representation of a generic type or method and maps all the instantiations of the generic type or method to the unique representation. ● The type Erasure process can be imagined as a translation from generic Java Source code back into regular Java Code. ● The Steps performed during type erasure : o Eliding Type Parameter : 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, or type Object if no bounds specified. Ex: <T> var; into Object var;
  • 14. Type Erasure ● The Steps performed during type erasure : o Eliding Type argument: When the compiler finds a parameterized type, i.e an instantiation of a generic types, then it removes the type arguments. Like : List<String>, Set<Long> and Map<String, ?> are translated to List, Set and Map respectively.
  • 15. 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. Example Before type Erasure:
  • 16. Bridge Method Example After type Erasure: ● Side Effect of type erasure is that two methods have identical signature before type erasure and different signature after type erasure.
  • 17. Bridge Method ● Under which circumstances is a bridge method generated ? o Bridge methods are necessary when a class implements a parameterized interface or extends a parametrized superclass and type erasure changes the arguments type of any of the inherited non-static method.
  • 18. Bridge Method ● The compiler must add the bridge methods even if the subclass does not override the inherited method.
  • 19. Type Erasure OF Parameterized Type ● The Erasure of a parameterized type is the type without any type argument (i.e the raw type). The definition extends to arrays and nested types.
  • 20. Type Erasure Of Type Parameter ● The type erasure of a type parameter is the erasure of its leftmost bound. The type erasure of an unbounded type parameter is type Object. Examples :
  • 21. Type Erasure Of Generic Type ● The Erasure of a method signature consisting of the same name and the erasures of all the formal method parameters types. Examples :
  • 22. Reficiation ● Representing type parameters and arguments of generic types and method at runtime. Reficiation is the opposite of type Erasure.
  • 23. Reifiable ● A type whose type information is fully available at run time, that is, a type that does not lose information in the course of type erasure. ● The following types are reifiable: o primitive types o non-generic (or non-parameterized) reference types o unbounded wildcard instantiations o raw types o arrays of any of the above ● The non-reifiable types, which lose type information as a side effect of type erasure, are: o instantiations of a generic type with at least one concrete type argument o instantiations of a generic type with at least one bounded wildcard as type argument ● Reifiable types are permitted in some places where non-reifiable types are disallowed. o as type in an instanceof expression o as component type of an array