SlideShare a Scribd company logo
1 of 13
Download to read offline
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

What's hot

Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMmanish kumar
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...Raffi Khatchadourian
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Raffi Khatchadourian
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10Terry Yoast
 
Poster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default MethodsPoster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default MethodsRaffi Khatchadourian
 
Java interfaces
Java interfacesJava interfaces
Java interfacesjehan1987
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Interface java
Interface java Interface java
Interface java atiafyrose
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMURaffi Khatchadourian
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritanceArjun Shanka
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5Sayed Ahmed
 

What's hot (20)

Lecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVMLecture - 2 Environment setup & JDK, JRE, JVM
Lecture - 2 Environment setup & JDK, JRE, JVM
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
Automated Refactoring of Legacy Java Software to Default Methods Talk at ICSE...
 
Control statements
Control statementsControl statements
Control statements
 
Java interface
Java interfaceJava interface
Java interface
 
Interface
InterfaceInterface
Interface
 
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...Towards Improving Interface Modularity in Legacy Java Software Through Automa...
Towards Improving Interface Modularity in Legacy Java Software Through Automa...
 
packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
9781111530532 ppt ch10
9781111530532 ppt ch109781111530532 ppt ch10
9781111530532 ppt ch10
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Poster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default MethodsPoster on Automated Refactoring of Legacy Java Software to Default Methods
Poster on Automated Refactoring of Legacy Java Software to Default Methods
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Interface java
Interface java Interface java
Interface java
 
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMUAutomated Refactoring of Legacy Java Software to Default Methods Talk at GMU
Automated Refactoring of Legacy Java Software to Default Methods Talk at GMU
 
Java interface
Java interfaceJava interface
Java interface
 
C# Basics
C# BasicsC# Basics
C# Basics
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Java Docs
Java DocsJava Docs
Java Docs
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 

Similar to Introducing generic types

Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in JavaGurpreet singh
 
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)Andrew Petryk
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxNadeemEzat
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasicswebuploader
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java GenericsYann-Gaël Guéhéneuc
 
On Java Generics, History, Use, Caveats v1.1
On Java Generics, History, Use, Caveats v1.1On Java Generics, History, Use, Caveats v1.1
On Java Generics, History, Use, Caveats v1.1Yann-Gaël Guéhéneuc
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Featuresindia_mani
 
Tiger: Java 5 Evolutions
Tiger: Java 5 EvolutionsTiger: Java 5 Evolutions
Tiger: Java 5 EvolutionsMarco Bresciani
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancementRakesh Madugula
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)David McCarter
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Androidemanuelez
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 

Similar to Introducing generic types (20)

Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
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)
 
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptxCS244 _Lec8_Generics_innerclasses_Lambda.pptx
CS244 _Lec8_Generics_innerclasses_Lambda.pptx
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
Java 17
Java 17Java 17
Java 17
 
On Parameterised Types and Java Generics
On Parameterised Types and Java GenericsOn Parameterised Types and Java Generics
On Parameterised Types and Java Generics
 
On Java Generics, History, Use, Caveats v1.1
On Java Generics, History, Use, Caveats v1.1On Java Generics, History, Use, Caveats v1.1
On Java Generics, History, Use, Caveats v1.1
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Generics
GenericsGenerics
Generics
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Tiger: Java 5 Evolutions
Tiger: Java 5 EvolutionsTiger: Java 5 Evolutions
Tiger: Java 5 Evolutions
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)Back-2-Basics: .NET Coding Standards For The Real World (2011)
Back-2-Basics: .NET Coding Standards For The Real World (2011)
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Junit4.0
Junit4.0Junit4.0
Junit4.0
 
Annotation Processing in Android
Annotation Processing in AndroidAnnotation Processing in Android
Annotation Processing in Android
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 

More from Ivelin Yanev

Quarkus Extensions Turbocharge for Java Microservices.pdf
Quarkus Extensions Turbocharge for Java Microservices.pdfQuarkus Extensions Turbocharge for Java Microservices.pdf
Quarkus Extensions Turbocharge for Java Microservices.pdfIvelin Yanev
 
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...
Empowering Your Java Applications with Quarkus. A New Era of Fast, Efficient,...Ivelin Yanev
 
Building flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on QuarkusBuilding flexible ETL pipelines with Apache Camel on Quarkus
Building flexible ETL pipelines with Apache Camel on QuarkusIvelin Yanev
 
Introducing java oop concepts
Introducing java oop conceptsIntroducing java oop concepts
Introducing java oop conceptsIvelin Yanev
 
Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Java features. Java 8, 9, 10, 11
Java features. Java 8, 9, 10, 11Ivelin Yanev
 
Java 9 modularity+
Java 9 modularity+Java 9 modularity+
Java 9 modularity+Ivelin Yanev
 
Intoduction Internet of Things
Intoduction Internet of ThingsIntoduction Internet of Things
Intoduction Internet of ThingsIvelin Yanev
 

More from Ivelin Yanev (11)

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

Recently uploaded

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
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.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
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.
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
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
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?Watsoo Telematics
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutionsmonugehlot87
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
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
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 

Recently uploaded (20)

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...
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
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...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
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
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
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
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
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...
 
What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?What are the features of Vehicle Tracking System?
What are the features of Vehicle Tracking System?
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
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
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
buds n tech IT solutions
buds n  tech IT                solutionsbuds n  tech IT                solutions
buds n tech IT solutions
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
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...
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 

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