SlideShare a Scribd company logo
12/5/19
Introducing Generic Types
Ivelin Yanev
12/5/19
OUTLINE
1.Introduction to Genetics
2.How to use Generics
3.Benefits of Generic
4.Bounded Types
5.Java Generics PECS – Producer Extends Consumer Super
2
12/5/19
Introduction to Genetics
Generics was added in Java 5 to provide compile-time type checking and
removing risk of ClassCastException that was common while working with
collection classes.
3
List list = new ArrayList();
list.add("abc");
list.add(new Integer(10));
for(Object obj : list){
String str=(String) obj;
}
Before Java 5
List<String> list1 = new ArrayList<String>();
// java 7 ? List<String> list1 = new ArrayList<>();
list1.add("abc");
//list1.add(new Integer(10)); //compiler error
for(String str : list1){
String s = str;
}
After Java 5
12/5/19
Type erasure
Regarding generics, this means that parameterized types are not stored in the
Bytecode.
4
List objects = new ArrayList();
List<String> strings = new ArrayList<String>();
List<Long> longs = new ArrayList<Long>();
Code:
0: new #2 // class java/util/ArrayList
3: dup
4: invokespecial #3 // Method java/util/ArrayList."<init>":()V
7: astore_1
8: new #2 // class java/util/ArrayList
11: dup
12: invokespecial #3 // Method java/util/ArrayList."<init>":()V
15: astore_2
16: new #2 // class java/util/ArrayList
19: dup
20: invokespecial #3 // Method java/util/ArrayList."<init>":()V
23: astore_3
24: return
12/5/19
Java-Bridge Method
Sometimes, the compiler will need to add a bridge method to a class to handle
situations in which the type erasure of an overriding method in a subclass does
not produce the same erasure as the method in the superclass.
5
class Bridge<T>
{
T t1;
Bridge(T t) {
t1 = t;
}
T getT() {
return t1;
}
}
class BridgeGen extends Bridge<Integer>
{
BridgeGen(Integer i) {
super(i);
}
Integer getT() {
return t1;
}
}
class Bridge
{
Object t1;
Bridge(Object t) {
t1 = t;
}
Object getT() {
return t1;
}
}
class BridgeGen extends Bridge
{
BridgeGen(Integer i) {
super(i);
}
Integer getT() {
return (Integer)t1;
}
Object getT() {
return getT();
}
}
12/5/19
How to use Generics
1. Generic Class
A generic class is defined with the following format:
The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the
type parameters (also called type variables) T1, T2, ..., and Tn.
2. Generic Interface
●
type-param-list is a comma-separated list of type parameters.
●
when a generic interface is implemented, you must specify the type arguments
6
class name<T1, T2, ..., Tn> { /* ... */ }
interface interfaceName<type-param-list> { // ...
}
class className<type-param-list> implements interfaceName<type-param-list> {
// ....
}
12/5/19
How to use Generics
3.Generic Method
The syntax for a generic method includes a list of type parameters, inside angle brackets, which
appears before the method's return type.
4. Generics Multiple Type Parameters
7
<type-Parameters> return_type method_name(parameter list)
{
// ..
}
public interface Map<K, V> {
...
}
12/5/19
Benefits of Generic
1. Stronger type checks at compile time:
- A Java compiler applies strong type checking to generic code and issues errors if the code
violates type safety.
- Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
8
List<String> list = new ArrayList<String>();
list.add("Bulgaria");
List holds only a String type of objects in generics.
It doesn’t allow to store other objects
2. Elimination of casts
List list = new ArrayList();
list.add("Bulgaria");
String s = (String) list.get(0);
List<String> list = new ArrayList<String>();
list.add("Bulgaria");
String s = list.get(0); // no cast
12/5/19
Bounded Types
There may be times when you want to restrict the types that can be used as
type arguments in a parameterized type
9
<T extends SuperClass>
This specifies that ‘T’ can only be replaced by ‘SuperClass’ or it subclasses.
Remember that extends clause is an inclusive bound. That means bound
includes ‘SuperClass’ also.
The type parameter can have multiple bounds:
<T extends B1 & B2 & B3>
12/5/19
Java Generics PECS
What is Wildcard?
The question mark (?), called the wildcard, represents an unknown type. The
wildcard is never used as a type argument for a generic method invocation, a
generic class instance creation, or a supertype.
10
boolean addAll(Collection<? extends E> c);
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l2104
public static <T> boolean addAll(Collection<? super T> c, T... elements);
https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l5457
12/5/19
Java Generics PECS
1. Upper Bounded Wildcards
This is the first part of PECS i.e. PE (Producer extends).
11
GenericType<? extends SuperClass>
2. Lower Bounded Wildcards
GenericType<? super SubClass>
This is the second part of PECS i.e. PE (Consumer extends).
12/5/19
Java Generics PECS
Summary
1. Use the <? extends T> wildcard if you need to retrieve object of type T from a
collection.
2. Use the <? super T> wildcard if you need to put objects of type T in a
collection.
3. If you need to satisfy both things, well, don’t use any wildcard. As simple as it
is.
4. In short, remember the term PECS. Producer extends Consumer super.
Really easy to remember.
12
12/5/19
Questions
1. There is a girl named Maria. She loves books and she has many books.
Create a liberally application that will manege will the all books. There are
different types of books. You have to create appropriate generic interface,
classes and methods.
2. Create school application:
- managing students(insert, delete and update)
-managing teachers(insert, delete and update)
You have to write above tasks within good practices. Make your code easy for
extend and generic.
13

More Related Content

PPTX
Java interface
PPTX
java interface and packages
PPTX
Interface in java
PPTX
Java interfaces
PPTX
Interfaces in java
PPTX
Unit3 part1-class
PPTX
Lecture - 5 Control Statement
PPT
Java interfaces
Java interface
java interface and packages
Interface in java
Java interfaces
Interfaces in java
Unit3 part1-class
Lecture - 5 Control Statement
Java interfaces

What's hot (20)

PPTX
Lecture - 2 Environment setup & JDK, JRE, JVM
PDF
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
PPS
Control statements
PPTX
Java interface
PPS
Interface
PDF
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
PPT
packages and interfaces
PPT
9781111530532 ppt ch10
PPT
PDF
Poster on Automated Refactoring of Legacy Java Software to Default Methods
PPTX
Java interfaces
PPTX
Interface in java ,multiple inheritance in java, interface implementation
PPTX
Interface java
PDF
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
PPTX
Java interface
PPTX
C# Basics
PDF
java-06inheritance
PPTX
PPT
PPTX
Object oriented programming in php 5
Lecture - 2 Environment setup & JDK, JRE, JVM
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Control statements
Java interface
Interface
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
packages and interfaces
9781111530532 ppt ch10
Poster on Automated Refactoring of Legacy Java Software to Default Methods
Java interfaces
Interface in java ,multiple inheritance in java, interface implementation
Interface java
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Java interface
C# Basics
java-06inheritance
Object oriented programming in php 5
Ad

Similar to Introducing generic types (20)

PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PPTX
Generic Collections and learn how to use it
PPTX
PPT
Generics in java
PPT
Generics Module 2Generics ModuleGenerics Module 2
PPT
Java Generics.ppt
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPTX
Collection in java to store multiple values.pptx
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PDF
Generic Programming
PPTX
Generics of JAVA
PDF
Generics Tutorial
PDF
117 A Outline 25
PPT
Generic programming in java
PDF
"Odisha's Living Legacy: Culture & Art".
PDF
Generics
PPT
Jdk1.5 Features
PPTX
Java generics final
PDF
Generics and collections in Java
Generic Types in Java (for ArtClub @ArtBrains Software)
Generic Collections and learn how to use it
Generics in java
Generics Module 2Generics ModuleGenerics Module 2
Java Generics.ppt
Generics Module 2Generics Module Generics Module 2.pptx
Collection in java to store multiple values.pptx
Java Generics Introduction - Syntax Advantages and Pitfalls
Generic Programming
Generics of JAVA
Generics Tutorial
117 A Outline 25
Generic programming in java
"Odisha's Living Legacy: Culture & Art".
Generics
Jdk1.5 Features
Java generics final
Generics and collections in Java
Ad

More from Ivelin Yanev (11)

PDF
Quarkus Extensions Turbocharge for Java Microservices.pdf
PDF
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
PDF
Project Loom
PPTX
Building flexible ETL pipelines with Apache Camel on Quarkus
PDF
Git collaboration
PDF
Java exeptions
PDF
Introducing java oop concepts
PDF
Java features. Java 8, 9, 10, 11
PDF
Design principles
PDF
Java 9 modularity+
PDF
Intoduction Internet of Things
Quarkus Extensions Turbocharge for Java Microservices.pdf
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
Project Loom
Building flexible ETL pipelines with Apache Camel on Quarkus
Git collaboration
Java exeptions
Introducing java oop concepts
Java features. Java 8, 9, 10, 11
Design principles
Java 9 modularity+
Intoduction Internet of Things

Recently uploaded (20)

PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
PDF
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
iTop VPN Free 5.6.0.5262 Crack latest version 2025
PPTX
Transform Your Business with a Software ERP System
PDF
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
PPTX
history of c programming in notes for students .pptx
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PDF
System and Network Administraation Chapter 3
PDF
Cost to Outsource Software Development in 2025
PPTX
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
PPTX
L1 - Introduction to python Backend.pptx
PDF
Softaken Excel to vCard Converter Software.pdf
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
Upgrade and Innovation Strategies for SAP ERP Customers
Adobe Premiere Pro 2025 (v24.5.0.057) Crack free
SAP S4 Hana Brochure 3 (PTS SYSTEMS AND SOLUTIONS)
CHAPTER 2 - PM Management and IT Context
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
iTop VPN Free 5.6.0.5262 Crack latest version 2025
Transform Your Business with a Software ERP System
Why TechBuilder is the Future of Pickup and Delivery App Development (1).pdf
history of c programming in notes for students .pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
System and Network Administraation Chapter 3
Cost to Outsource Software Development in 2025
Agentic AI : A Practical Guide. Undersating, Implementing and Scaling Autono...
L1 - Introduction to python Backend.pptx
Softaken Excel to vCard Converter Software.pdf
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
PTS Company Brochure 2025 (1).pdf.......
Why Generative AI is the Future of Content, Code & Creativity?

Introducing generic types

  • 2. 12/5/19 OUTLINE 1.Introduction to Genetics 2.How to use Generics 3.Benefits of Generic 4.Bounded Types 5.Java Generics PECS – Producer Extends Consumer Super 2
  • 3. 12/5/19 Introduction to Genetics Generics was added in Java 5 to provide compile-time type checking and removing risk of ClassCastException that was common while working with collection classes. 3 List list = new ArrayList(); list.add("abc"); list.add(new Integer(10)); for(Object obj : list){ String str=(String) obj; } Before Java 5 List<String> list1 = new ArrayList<String>(); // java 7 ? List<String> list1 = new ArrayList<>(); list1.add("abc"); //list1.add(new Integer(10)); //compiler error for(String str : list1){ String s = str; } After Java 5
  • 4. 12/5/19 Type erasure Regarding generics, this means that parameterized types are not stored in the Bytecode. 4 List objects = new ArrayList(); List<String> strings = new ArrayList<String>(); List<Long> longs = new ArrayList<Long>(); Code: 0: new #2 // class java/util/ArrayList 3: dup 4: invokespecial #3 // Method java/util/ArrayList."<init>":()V 7: astore_1 8: new #2 // class java/util/ArrayList 11: dup 12: invokespecial #3 // Method java/util/ArrayList."<init>":()V 15: astore_2 16: new #2 // class java/util/ArrayList 19: dup 20: invokespecial #3 // Method java/util/ArrayList."<init>":()V 23: astore_3 24: return
  • 5. 12/5/19 Java-Bridge Method Sometimes, the compiler will need to add a bridge method to a class to handle situations in which the type erasure of an overriding method in a subclass does not produce the same erasure as the method in the superclass. 5 class Bridge<T> { T t1; Bridge(T t) { t1 = t; } T getT() { return t1; } } class BridgeGen extends Bridge<Integer> { BridgeGen(Integer i) { super(i); } Integer getT() { return t1; } } class Bridge { Object t1; Bridge(Object t) { t1 = t; } Object getT() { return t1; } } class BridgeGen extends Bridge { BridgeGen(Integer i) { super(i); } Integer getT() { return (Integer)t1; } Object getT() { return getT(); } }
  • 6. 12/5/19 How to use Generics 1. Generic Class A generic class is defined with the following format: The type parameter section, delimited by angle brackets (<>), follows the class name. It specifies the type parameters (also called type variables) T1, T2, ..., and Tn. 2. Generic Interface ● type-param-list is a comma-separated list of type parameters. ● when a generic interface is implemented, you must specify the type arguments 6 class name<T1, T2, ..., Tn> { /* ... */ } interface interfaceName<type-param-list> { // ... } class className<type-param-list> implements interfaceName<type-param-list> { // .... }
  • 7. 12/5/19 How to use Generics 3.Generic Method The syntax for a generic method includes a list of type parameters, inside angle brackets, which appears before the method's return type. 4. Generics Multiple Type Parameters 7 <type-Parameters> return_type method_name(parameter list) { // .. } public interface Map<K, V> { ... }
  • 8. 12/5/19 Benefits of Generic 1. Stronger type checks at compile time: - A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. - Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find. 8 List<String> list = new ArrayList<String>(); list.add("Bulgaria"); List holds only a String type of objects in generics. It doesn’t allow to store other objects 2. Elimination of casts List list = new ArrayList(); list.add("Bulgaria"); String s = (String) list.get(0); List<String> list = new ArrayList<String>(); list.add("Bulgaria"); String s = list.get(0); // no cast
  • 9. 12/5/19 Bounded Types There may be times when you want to restrict the types that can be used as type arguments in a parameterized type 9 <T extends SuperClass> This specifies that ‘T’ can only be replaced by ‘SuperClass’ or it subclasses. Remember that extends clause is an inclusive bound. That means bound includes ‘SuperClass’ also. The type parameter can have multiple bounds: <T extends B1 & B2 & B3>
  • 10. 12/5/19 Java Generics PECS What is Wildcard? The question mark (?), called the wildcard, represents an unknown type. The wildcard is never used as a type argument for a generic method invocation, a generic class instance creation, or a supertype. 10 boolean addAll(Collection<? extends E> c); https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l2104 public static <T> boolean addAll(Collection<? super T> c, T... elements); https://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Collections.java#l5457
  • 11. 12/5/19 Java Generics PECS 1. Upper Bounded Wildcards This is the first part of PECS i.e. PE (Producer extends). 11 GenericType<? extends SuperClass> 2. Lower Bounded Wildcards GenericType<? super SubClass> This is the second part of PECS i.e. PE (Consumer extends).
  • 12. 12/5/19 Java Generics PECS Summary 1. Use the <? extends T> wildcard if you need to retrieve object of type T from a collection. 2. Use the <? super T> wildcard if you need to put objects of type T in a collection. 3. If you need to satisfy both things, well, don’t use any wildcard. As simple as it is. 4. In short, remember the term PECS. Producer extends Consumer super. Really easy to remember. 12
  • 13. 12/5/19 Questions 1. There is a girl named Maria. She loves books and she has many books. Create a liberally application that will manege will the all books. There are different types of books. You have to create appropriate generic interface, classes and methods. 2. Create school application: - managing students(insert, delete and update) -managing teachers(insert, delete and update) You have to write above tasks within good practices. Make your code easy for extend and generic. 13