2
Most read
6
Most read
10
Most read
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

PDF
Generics and collections in Java
PPT
Generics in java
PPTX
Java Generics
PDF
Java Generics - by Example
PDF
Generic Programming
PPT
Generic Programming seminar
PPT
Jdk1.5 Features
PPT
Chapter 8 - Exceptions and Assertions Edit summary
Generics and collections in Java
Generics in java
Java Generics
Java Generics - by Example
Generic Programming
Generic Programming seminar
Jdk1.5 Features
Chapter 8 - Exceptions and Assertions Edit summary

What's hot (20)

PPT
Chapter 9 - Characters and Strings
PPT
Effective Java - Generics
PPT
Java Generics
PPT
M C6java3
PPT
Chapter 2 - Getting Started with Java
PPT
Core java concepts
PPTX
Lecture 4_Java Method-constructor_imp_keywords
PPTX
Java basics variables
PPTX
Java fundamentals
PPTX
Oop2011 actor presentation_stal
PPTX
Lecture - 3 Variables-data type_operators_oops concept
PPTX
Lecture 6 inheritance
PPT
Unit 1 Java
PPT
Java tutorial for Beginners and Entry Level
PPTX
Oop2010 Scala Presentation Stal
PPT
M C6java2
PPTX
Qcon2011 functions rockpresentation_scala
PPTX
Java generics
PPT
Chapter 7 - Defining Your Own Classes - Part II
PPT
Object-Oriented Programming Using C++
Chapter 9 - Characters and Strings
Effective Java - Generics
Java Generics
M C6java3
Chapter 2 - Getting Started with Java
Core java concepts
Lecture 4_Java Method-constructor_imp_keywords
Java basics variables
Java fundamentals
Oop2011 actor presentation_stal
Lecture - 3 Variables-data type_operators_oops concept
Lecture 6 inheritance
Unit 1 Java
Java tutorial for Beginners and Entry Level
Oop2010 Scala Presentation Stal
M C6java2
Qcon2011 functions rockpresentation_scala
Java generics
Chapter 7 - Defining Your Own Classes - Part II
Object-Oriented Programming Using C++
Ad

Similar to Generic Programming in java (20)

PPTX
Java generics(Under The Hood Of The Compiler) by Harmeet singh
PPTX
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PDF
Generics Tutorial
PDF
117 A Outline 25
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPT
Generics lecture
PDF
Generics Tutorial
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PDF
The Sincerest Form of Flattery
PPTX
Java generics final
PPTX
19eac8bc6ce04662agga7g53200208b16c5.pptx
PPT
Java Generics.ppt
PPT
java training faridabad
PPT
Java Tutorials
PDF
Introducing generic types
PPTX
21CS642 Module 2 Generics PPT.pptx VI SEM CSE
PPT
core java
PPTX
Generics of JAVA
Java generics(Under The Hood Of The Compiler) by Harmeet singh
Java Generics Introduction - Syntax Advantages and Pitfalls
Generics Tutorial
117 A Outline 25
Generics Module 2Generics Module Generics Module 2.pptx
Generics lecture
Generics Tutorial
Generic Types in Java (for ArtClub @ArtBrains Software)
The Sincerest Form of Flattery
Java generics final
19eac8bc6ce04662agga7g53200208b16c5.pptx
Java Generics.ppt
java training faridabad
Java Tutorials
Introducing generic types
21CS642 Module 2 Generics PPT.pptx VI SEM CSE
core java
Generics of JAVA
Ad

Recently uploaded (20)

PDF
Top AI Tools for Project Managers: My 2025 AI Stack
PDF
Mobile App for Guard Tour and Reporting.pdf
PPTX
Comprehensive Guide to Digital Image Processing Concepts and Applications
PPTX
AI Tools Revolutionizing Software Development Workflows
PDF
Mobile App Backend Development with WordPress REST API: The Complete eBook
PPTX
Chapter_05_System Modeling for software engineering
PPTX
Relevance Tuning with Genetic Algorithms
PDF
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
PPTX
Beige and Black Minimalist Project Deck Presentation (1).pptx
PPTX
Folder Lock 10.1.9 Crack With Serial Key
PPTX
Greedy best-first search algorithm always selects the path which appears best...
PDF
What Makes a Great Data Visualization Consulting Service.pdf
PPTX
ESDS_SAP Application Cloud Offerings.pptx
PPTX
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
PDF
Top 10 Project Management Software for Small Teams in 2025.pdf
PDF
Adlice Diag Crack With Serial Key Free Download 2025
PDF
infoteam HELLAS company profile 2025 presentation
PPTX
SAP Business AI_L1 Overview_EXTERNAL.pptx
PDF
Module 1 - Introduction to Generative AI.pdf
PPTX
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...
Top AI Tools for Project Managers: My 2025 AI Stack
Mobile App for Guard Tour and Reporting.pdf
Comprehensive Guide to Digital Image Processing Concepts and Applications
AI Tools Revolutionizing Software Development Workflows
Mobile App Backend Development with WordPress REST API: The Complete eBook
Chapter_05_System Modeling for software engineering
Relevance Tuning with Genetic Algorithms
Streamlining Project Management in Microsoft Project, Planner, and Teams with...
Beige and Black Minimalist Project Deck Presentation (1).pptx
Folder Lock 10.1.9 Crack With Serial Key
Greedy best-first search algorithm always selects the path which appears best...
What Makes a Great Data Visualization Consulting Service.pdf
ESDS_SAP Application Cloud Offerings.pptx
Swiggy API Scraping A Comprehensive Guide on Data Sets and Applications.pptx
Top 10 Project Management Software for Small Teams in 2025.pdf
Adlice Diag Crack With Serial Key Free Download 2025
infoteam HELLAS company profile 2025 presentation
SAP Business AI_L1 Overview_EXTERNAL.pptx
Module 1 - Introduction to Generative AI.pdf
Post-Migration Optimization Playbook: Getting the Most Out of Your New Adobe ...

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