SlideShare a Scribd company logo
JAVA GENERICS: BY EXAMPLE
ganesh@codeops.tech
Ganesh Samarthyam
Java Generics - by Example
Java Generics - by Example
Java Generics - by Example
Why should I use
generics?
Avoid repetition
Reduce ctrl+c and ctrl+v
Generics: Type safety
Source code
https://github.com/CodeOpsTech/JavaGenerics
First program
// This program shows container implementation using generics
class BoxPrinter<T> {
private T val;
public BoxPrinter(T arg) {
val = arg;
}
public String toString() {
return "[" + val + "]";
}
}
class BoxPrinterTest {
public static void main(String []args) {
BoxPrinter<Integer> value1 = new BoxPrinter<Integer>(new Integer(10));
System.out.println(value1);
BoxPrinter<String> value2 = new BoxPrinter<String>("Hello world");
System.out.println(value2);
}
}
[10]
[Hello world]
Another example
// It demonstrates the usage of generics in defining classes
class Pair<T1, T2> {
T1 object1;
T2 object2;
Pair(T1 one, T2 two) {
object1 = one;
object2 = two;
}
public T1 getFirst() {
return object1;
}
public T2 getSecond() {
return object2;
}
}
class PairTest {
public static void main(String []args) {
Pair<Integer, String> worldCup = new Pair<Integer, String>(2018, "Russia");
System.out.println("World cup " + worldCup.getFirst() +
" in " + worldCup.getSecond());
}
}
World cup 2018 in Russia
Type checking
Pair<Integer, String> worldCup = new Pair<String, String>(2018, "Russia");
TestPair.java:20: cannot find symbol
symbol : constructor Pair(int,java.lang.String)
location: class Pair<java.lang.String,java.lang.String>
Type checking
Pair<Integer, String> worldCup = new Pair<Number, String>(2018, “Russia");
TestPair.java:20: incompatible types
found : Pair<java.lang.Number,java.lang.String>
required: Pair<java.lang.Integer,java.lang.String>
Yet another example
// This program shows how to use generics in your programs
class PairOfT<T> {
T object1;
T object2;
PairOfT(T one, T two) {
object1 = one;
object2 = two;
}
public T getFirst() {
return object1;
}
public T getSecond() {
return object2;
}
}
Type checking
PairOfT<Integer, String> worldCup = new PairOfT<Integer, String>(2018, "Russia");
Type checking
PairOfT<String> worldCup = new PairOfT<String>(2018, “Russia");
TestPair.java:20: cannot find symbol
symbol : constructor PairOfT(int,java.lang.String)
location: class PairOfT<java.lang.String>
PairOfT<String> worldCup = new PairOfT<String>(2018, "Russia");
PairOfT<String> worldCup = new PairOfT<String>("2018", "Russia");
Java => Too much typing
Diamond syntax
// This program shows the usage of the diamond syntax when using generics
class Pair<T1, T2> {
T1 object1;
T2 object2;
Pair(T1 one, T2 two) {
object1 = one;
object2 = two;
}
public T1 getFirst() {
return object1;
}
public T2 getSecond() {
return object2;
}
}
class TestPair {
public static void main(String []args) {
Pair<Integer, String> worldCup = new Pair<>(2018, "Russia");
System.out.println("World cup " + worldCup.getFirst() + " in " + worldCup.getSecond());
}
}
World cup 2018 in Russia
Forgetting < and >
Pair<Integer, String> worldCup = new Pair(2018, "Russia");
Pair.java:19: warning: [unchecked] unchecked call to Pair(T1,T2) as a member of the
raw type Pair
Pair<Integer, String> worldCup = new Pair(2018, "Russia");
^
where T1,T2 are type-variables:
T1 extends Object declared in class Pair
T2 extends Object declared in class Pair
Pair.java:19: warning: [unchecked] unchecked conversion
Pair<Integer, String> worldCup = new Pair(2018, "Russia");
^
required: Pair<Integer,String>
found: Pair
2 warnings
Type erasure
Implementation of generics is static in nature, which means that the
Java compiler interprets the generics specified in the source code and
replaces the generic code with concrete types. This is referred to as
type erasure. After compilation, the code looks similar to what a
developer would have written with concrete types.
Type erasure
Type erasure
T mem = new T(); // wrong usage - compiler error
Type erasure
T[] amem = new T[100]; // wrong usage - compiler error
Type erasure
class X<T> {
T instanceMem; // okay
static T statMem; // wrong usage - compiler error
}
Generics - limitations
You cannot instantiate a generic type with primitive
types, for example, List<int> is not allowed. However,
you can use boxed primitive types like List<Integer>.
Raw types
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
class RawTest1 {
public static void main(String []args) {
List list = new LinkedList();
list.add("First");
list.add("Second");
List<String> strList = list; //#1
for(Iterator<String> itemItr = strList.iterator(); itemItr.hasNext();)
System.out.println("Item: " + itemItr.next());
List<String> strList2 = new LinkedList<>();
strList2.add("First");
strList2.add("Second");
List list2 = strList2; //#2
for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();)
System.out.println("Item: " + itemItr.next());
}
}
Item: First
Item: Second
Item: First
Item: Second
$ javac RawTest1.java
Note: RawTest1.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Raw types
$ javac -Xlint:unchecked RawTest1.java
RawTest1.java:14: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
list.add("First");
^
where E is a type-variable:
E extends Object declared in interface List
RawTest1.java:15: warning: [unchecked] unchecked call to add(E) as a member of the raw type List
list.add("Second");
^
where E is a type-variable:
E extends Object declared in interface List
RawTest1.java:16: warning: [unchecked] unchecked conversion
List<String> strList = list; //#1
^
required: List<String>
found: List
RawTest1.java:24: warning: [unchecked] unchecked conversion
for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();)
^
required: Iterator<String>
found: Iterator
4 warnings
$
Raw types
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
class RawTest2 {
public static void main(String []args) {
List list = new LinkedList();
list.add("First");
list.add("Second");
List<String> strList = list;
strList.add(10); // #1: generates compiler error
for(Iterator<String> itemItr = strList.iterator(); itemItr.hasNext();)
System.out.println("Item : " + itemItr.next());
List<String> strList2 = new LinkedList<>();
strList2.add("First");
strList2.add("Second");
List list2 = strList2;
list2.add(10); // #2: compiles fine, results in runtime exception
for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();)
System.out.println("Item : " + itemItr.next());
}
}
Raw types
List<String> strList2 = new LinkedList<>();
strList2.add("First");
strList2.add("Second");
List list2 = strList2;
list2.add(10); // #2: compiles fine, results in runtime exception
for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();)
System.out.println("Item : " + itemItr.next());
Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot
be cast to java.lang.String at RawTest2.main(RawTest2.java:27)
Best practice
Avoid using raw types of generic types
Generic methods
// This program demonstrates generic methods
import java.util.List;
import java.util.ArrayList;
class Utilities {
public static <T> void fill(List<T> list, T val) {
for(int i = 0; i < list.size(); i++)
list.set(i, val);
}
}
class UtilitiesTest {
public static void main(String []args) {
List<Integer> intList = new ArrayList<Integer>();
intList.add(10);
intList.add(20);
System.out.println("The original list is: " + intList);
Utilities.fill(intList, 100);
System.out.println("The list after calling Utilities.fill() is: " + intList);
}
}
The original list is: [10, 20]
The list after calling Utilities.fill() is: [100, 100]
Generics and sub typing
Subtyping works for class types: you can assign a
derived type object to its base type reference.
However, subtyping does not work for generic type
parameters: you cannot assign a derived generic type
parameter to a base type parameter.
Generics and sub typing
// illegal code – assume that the following intialization is allowed
List<Number> intList = new ArrayList<Integer>();
intList.add(new Integer(10)); // okay
intList.add(new Float(10.0f)); // oops!
Generics and sub typing
List<Number> intList = new ArrayList<Integer>();
WildCardUse.java:6: incompatible types
found : java.util.ArrayList<java.lang.Integer>
required: java.util.List<java.lang.Number>
List<?> wildCardList = new ArrayList<Integer>();
Wildcard types
Type parameters for generics have a limitation:
generic type parameters should match exactly for
assignments. To overcome this subtyping
problem, you can use wildcard types.
Wildcard types
Use a wildcard to indicate that it can match for any type: List<?>, you mean that
it is a List of any type—in other words, you can say it is a “list of unknowns!
How about this “workaround”?
WildCardUse.java:6: incompatible types
found : java.util.ArrayList<java.lang.Integer>
required: java.util.List<java.lang.Object>
List<Object> numList = new ArrayList<Integer>();
List<Object> numList = new ArrayList<Integer>();
Wildcard use
// This program demonstrates the usage of wild card parameters
import java.util.List;
import java.util.ArrayList;
class WildCardUse {
static void printList(List<?> list){
for(Object element: list)
System.out.println("[" + element + "]");
}
public static void main(String []args) {
List<Integer> list = new ArrayList<>();
list.add(10);
list.add(100);
printList(list);
List<String> strList = new ArrayList<>();
strList.add("10");
strList.add("100");
printList(strList);
}
} [10]
[100]
[10]
[100]
Limitations of Wildcards
List<?> wildCardList = new ArrayList<Integer>();
wildCardList.add(new Integer(10));
System.out.println(wildCardList);
WildCardUse.java:7: cannot find symbol
symbol : method add(java.lang.Integer)
location: interface java.util.List<capture#145 of ? extends java.lang.Number>
wildCardList.add(new Integer(10));
Wildcard types
In general, when you use wildcard parameters,
you cannot call methods that modify the object. If
youtry to modify, the compiler will give you
confusing error messages. However, you can call
methods that access the object.
More about generics
• It’s possible to define or declare generic methods in an interface or a
class even if the class or the interface itself is not generic.
• A generic class used without type arguments is known as a raw type.
Of course, raw types are not type safe. Java supports raw types so that
it is possible to use the generic type in code that is older than Java 5
(note that generics were introduced in Java 5). The compiler generates
a warning when you use raw types in your code. You may use
@SuppressWarnings({ "unchecked" }) to suppress the warning
associated with raw types.
• List<?> is a supertype of any List type, which means you can pass
List<Integer>, or List<String>, or even List<Object> where List<?>
is expected.
<? super T> and <? extends T>
<R> Stream<R> map(Function<? super T,? extends R> transform)
Duck<? super Color> or Duck<? extends Color>
Generics: Code can be terrible to read
Question time
Books to read
Books to read
ocpjava.wordpress.com
Image credits
❖ http://www.ookii.org/misc/cup_of_t.jpg
❖ http://thumbnails-visually.netdna-ssl.com/tea-or-coffee_52612a16dfce8_w1500.png
❖ http://i1.wp.com/limpingchicken.com/wp-content/uploads/2013/04/question-chicken-l.jpg?
resize=450%2C232
❖ https://4.bp.blogspot.com/-knt6r-h4tzE/VvU-7QrZCyI/AAAAAAAAFYs/
welz0JLVgbgOtfRSl98OxztA8Sb4VXxCg/s1600/Generics%2Bin%2BJava.png
❖ http://homepages.inf.ed.ac.uk/wadler/gj/gj-back-full.jpg
❖ http://kaczanowscy.pl/tomek/sites/default/files/generic_monster.jpeg
❖ https://s-media-cache-ak0.pinimg.com/736x/f7/b1/47/f7b147bfbc8332a2e3f2ba3c44a8e6d2.jpg
❖ https://avatars.githubusercontent.com/u/2187012?v=3
❖ http://image-7.verycd.com/fb2e74a15a36c4e7c1b6d4b1eb148af1104235/lrg.jpg
❖ http://regmedia.co.uk/2007/05/03/cartoon_duck.jpg
❖ https://m.popkey.co/48a22d/VWZR6.gif
❖ http://www.rawstory.com/wp-content/uploads/2012/07/boozehound-shutterstock.jpg
❖ http://www.fantasyfootballgeek.co.uk/wp-content/uploads/2016/04/wildcard-1-1.jpg
❖ https://i.ytimg.com/vi/XB0pGnzsAZI/hqdefault.jpg
ganesh@codeops.tech @GSamarthyam
www.codeops.tech slideshare.net/sgganesh
+91 98801 64463 bit.ly/sgganesh

More Related Content

PDF
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
PDF
Java Class Design
Ganesh Samarthyam
 
PDF
Java Concurrency by Example
Ganesh Samarthyam
 
PDF
Java Class Design
Ganesh Samarthyam
 
PDF
Sailing with Java 8 Streams
Ganesh Samarthyam
 
PDF
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
PDF
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
PDF
Functional Algebra: Monoids Applied
Susan Potter
 
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Java Class Design
Ganesh Samarthyam
 
Java Concurrency by Example
Ganesh Samarthyam
 
Java Class Design
Ganesh Samarthyam
 
Sailing with Java 8 Streams
Ganesh Samarthyam
 
Design Patterns - Compiler Case Study - Hands-on Examples
Ganesh Samarthyam
 
Coding Guidelines - Crafting Clean Code
Ganesh Samarthyam
 
Functional Algebra: Monoids Applied
Susan Potter
 

What's hot (19)

KEY
Why Learn Python?
Christine Cheung
 
PPTX
Java Generics
Zülfikar Karakaya
 
PDF
Java Simple Programs
Upender Upr
 
PDF
Java VS Python
Simone Federici
 
DOC
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
PDF
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Susan Potter
 
PPT
Java Generics for Dummies
knutmork
 
PPTX
Use of Apache Commons and Utilities
Pramod Kumar
 
PDF
Java programming-examples
Mumbai Academisc
 
PDF
Java 8 Lambda Expressions
Scott Leberknight
 
PDF
Java programs
Mukund Gandrakota
 
PPTX
Unit testing concurrent code
Rafael Winterhalter
 
DOCX
Java practical
shweta-sharma99
 
ODP
Java Generics
Carol McDonald
 
PDF
java sockets
Enam Ahmed Shahaz
 
PDF
Advanced Java Practical File
Soumya Behera
 
PPTX
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
PPT
Initial Java Core Concept
Rays Technologies
 
PPT
OOP Core Concept
Rays Technologies
 
Why Learn Python?
Christine Cheung
 
Java Generics
Zülfikar Karakaya
 
Java Simple Programs
Upender Upr
 
Java VS Python
Simone Federici
 
Final JAVA Practical of BCA SEM-5.
Nishan Barot
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Susan Potter
 
Java Generics for Dummies
knutmork
 
Use of Apache Commons and Utilities
Pramod Kumar
 
Java programming-examples
Mumbai Academisc
 
Java 8 Lambda Expressions
Scott Leberknight
 
Java programs
Mukund Gandrakota
 
Unit testing concurrent code
Rafael Winterhalter
 
Java practical
shweta-sharma99
 
Java Generics
Carol McDonald
 
java sockets
Enam Ahmed Shahaz
 
Advanced Java Practical File
Soumya Behera
 
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 
Initial Java Core Concept
Rays Technologies
 
OOP Core Concept
Rays Technologies
 
Ad

Viewers also liked (8)

PDF
Writing an Abstract - Template (for research papers)
Ganesh Samarthyam
 
PDF
Design Smell Descriptions - Summary Sheet
Ganesh Samarthyam
 
PDF
Refactoring guided by design principles driven by technical debt
Ganesh Samarthyam
 
PDF
Tools for Refactoring
Ganesh Samarthyam
 
PDF
Refactoring for Software Architecture Smells - International Workshop on Refa...
Ganesh Samarthyam
 
PPTX
Как найти первую работу и как с нее не вылететь
Sergey Nemchinsky
 
PDF
Let's Go: Introduction to Google's Go Programming Language
Ganesh Samarthyam
 
PDF
Bangalore Container Conference 2017 - Poster
Ganesh Samarthyam
 
Writing an Abstract - Template (for research papers)
Ganesh Samarthyam
 
Design Smell Descriptions - Summary Sheet
Ganesh Samarthyam
 
Refactoring guided by design principles driven by technical debt
Ganesh Samarthyam
 
Tools for Refactoring
Ganesh Samarthyam
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Ganesh Samarthyam
 
Как найти первую работу и как с нее не вылететь
Sergey Nemchinsky
 
Let's Go: Introduction to Google's Go Programming Language
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Poster
Ganesh Samarthyam
 
Ad

Similar to Java Generics - by Example (20)

PDF
Javase5generics
imypraz
 
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
PPT
Effective Java - Generics
Roshan Deniyage
 
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
PDF
Effective Java Second Edition
losalamos
 
PDF
117 A Outline 25
wasntgosu
 
PDF
Generics Tutorial
wasntgosu
 
PPTX
Java generics final
Akshay Chaudhari
 
PPTX
Generics Module 2Generics Module Generics Module 2.pptx
AlvasCSE
 
PDF
08-L19-Generics.pdfGenerics Module 2.pptx
AlvasCSE
 
PDF
"Odisha's Living Legacy: Culture & Art".
biswajitbaral8926030
 
PPTX
Generics
Shahjahan Samoon
 
PDF
Generics Tutorial
wasntgosu
 
PPT
Generics lecture
Bradford Bazemore
 
PPT
Java Generics.ppt
brayazar
 
PPTX
Java Generics
DeeptiJava
 
PPT
GenericsFinal.ppt
Virat10366
 
PPTX
Generic Collections and learn how to use it
halaplay385
 
ODP
javasebeyondbasics
webuploader
 
PDF
Introducing generic types
Ivelin Yanev
 
Javase5generics
imypraz
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Effective Java - Generics
Roshan Deniyage
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Effective Java Second Edition
losalamos
 
117 A Outline 25
wasntgosu
 
Generics Tutorial
wasntgosu
 
Java generics final
Akshay Chaudhari
 
Generics Module 2Generics Module Generics Module 2.pptx
AlvasCSE
 
08-L19-Generics.pdfGenerics Module 2.pptx
AlvasCSE
 
"Odisha's Living Legacy: Culture & Art".
biswajitbaral8926030
 
Generics Tutorial
wasntgosu
 
Generics lecture
Bradford Bazemore
 
Java Generics.ppt
brayazar
 
Java Generics
DeeptiJava
 
GenericsFinal.ppt
Virat10366
 
Generic Collections and learn how to use it
halaplay385
 
javasebeyondbasics
webuploader
 
Introducing generic types
Ivelin Yanev
 

More from Ganesh Samarthyam (20)

PDF
Wonders of the Sea
Ganesh Samarthyam
 
PDF
Animals - for kids
Ganesh Samarthyam
 
PDF
Applying Refactoring Tools in Practice
Ganesh Samarthyam
 
PDF
CFP - 1st Workshop on “AI Meets Blockchain”
Ganesh Samarthyam
 
PDF
Great Coding Skills Aren't Enough
Ganesh Samarthyam
 
PDF
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
PDF
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
PDF
Software Design in Practice (with Java examples)
Ganesh Samarthyam
 
PDF
OO Design and Design Patterns in C++
Ganesh Samarthyam
 
PDF
Bangalore Container Conference 2017 - Sponsorship Deck
Ganesh Samarthyam
 
PPT
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
PDF
Java Generics - Quiz Questions
Ganesh Samarthyam
 
PDF
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
PDF
Docker by Example - Quiz
Ganesh Samarthyam
 
PDF
Core Java: Best practices and bytecodes quiz
Ganesh Samarthyam
 
PDF
Refactoring for Software Architecture Smells - International Workshop on Refa...
Ganesh Samarthyam
 
PDF
Refactoring for Software Design Smells - XP Conference - August 20th 2016
Ganesh Samarthyam
 
PDF
How to Write Abstracts (for White Papers, Research Papers, ...)
Ganesh Samarthyam
 
PDF
Refactoring for Software Design Smells - Tech Talk
Ganesh Samarthyam
 
PDF
Java Concurrency - Quiz Questions
Ganesh Samarthyam
 
Wonders of the Sea
Ganesh Samarthyam
 
Animals - for kids
Ganesh Samarthyam
 
Applying Refactoring Tools in Practice
Ganesh Samarthyam
 
CFP - 1st Workshop on “AI Meets Blockchain”
Ganesh Samarthyam
 
Great Coding Skills Aren't Enough
Ganesh Samarthyam
 
College Project - Java Disassembler - Description
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Brief Presentation
Ganesh Samarthyam
 
Software Design in Practice (with Java examples)
Ganesh Samarthyam
 
OO Design and Design Patterns in C++
Ganesh Samarthyam
 
Bangalore Container Conference 2017 - Sponsorship Deck
Ganesh Samarthyam
 
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
Java Generics - Quiz Questions
Ganesh Samarthyam
 
Software Architecture - Quiz Questions
Ganesh Samarthyam
 
Docker by Example - Quiz
Ganesh Samarthyam
 
Core Java: Best practices and bytecodes quiz
Ganesh Samarthyam
 
Refactoring for Software Architecture Smells - International Workshop on Refa...
Ganesh Samarthyam
 
Refactoring for Software Design Smells - XP Conference - August 20th 2016
Ganesh Samarthyam
 
How to Write Abstracts (for White Papers, Research Papers, ...)
Ganesh Samarthyam
 
Refactoring for Software Design Smells - Tech Talk
Ganesh Samarthyam
 
Java Concurrency - Quiz Questions
Ganesh Samarthyam
 

Recently uploaded (20)

PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PDF
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
PDF
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PDF
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pdf
Certivo Inc
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PDF
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPT
Activate_Methodology_Summary presentatio
annapureddyn
 
PPTX
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
Build Multi-agent using Agent Development Kit
FadyIbrahim23
 
Jenkins: An open-source automation server powering CI/CD Automation
SaikatBasu37
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pdf
Certivo Inc
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
The Role of Automation and AI in EHS Management for Data Centers.pdf
TECH EHS Solution
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
49785682629390197565_LRN3014_Migrating_the_Beast.pdf
Abilash868456
 
Presentation about variables and constant.pptx
kr2589474
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Activate_Methodology_Summary presentatio
annapureddyn
 
Presentation of Computer CLASS 2 .pptx
darshilchaudhary558
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Multi-factor Authentication (MFA) requirement for Microsoft 365 Admin Center_...
Q-Advise
 

Java Generics - by Example

  • 1. JAVA GENERICS: BY EXAMPLE [email protected] Ganesh Samarthyam
  • 5. Why should I use generics?
  • 10. First program // This program shows container implementation using generics class BoxPrinter<T> { private T val; public BoxPrinter(T arg) { val = arg; } public String toString() { return "[" + val + "]"; } } class BoxPrinterTest { public static void main(String []args) { BoxPrinter<Integer> value1 = new BoxPrinter<Integer>(new Integer(10)); System.out.println(value1); BoxPrinter<String> value2 = new BoxPrinter<String>("Hello world"); System.out.println(value2); } } [10] [Hello world]
  • 11. Another example // It demonstrates the usage of generics in defining classes class Pair<T1, T2> { T1 object1; T2 object2; Pair(T1 one, T2 two) { object1 = one; object2 = two; } public T1 getFirst() { return object1; } public T2 getSecond() { return object2; } } class PairTest { public static void main(String []args) { Pair<Integer, String> worldCup = new Pair<Integer, String>(2018, "Russia"); System.out.println("World cup " + worldCup.getFirst() + " in " + worldCup.getSecond()); } } World cup 2018 in Russia
  • 12. Type checking Pair<Integer, String> worldCup = new Pair<String, String>(2018, "Russia"); TestPair.java:20: cannot find symbol symbol : constructor Pair(int,java.lang.String) location: class Pair<java.lang.String,java.lang.String>
  • 13. Type checking Pair<Integer, String> worldCup = new Pair<Number, String>(2018, “Russia"); TestPair.java:20: incompatible types found : Pair<java.lang.Number,java.lang.String> required: Pair<java.lang.Integer,java.lang.String>
  • 14. Yet another example // This program shows how to use generics in your programs class PairOfT<T> { T object1; T object2; PairOfT(T one, T two) { object1 = one; object2 = two; } public T getFirst() { return object1; } public T getSecond() { return object2; } }
  • 15. Type checking PairOfT<Integer, String> worldCup = new PairOfT<Integer, String>(2018, "Russia");
  • 16. Type checking PairOfT<String> worldCup = new PairOfT<String>(2018, “Russia"); TestPair.java:20: cannot find symbol symbol : constructor PairOfT(int,java.lang.String) location: class PairOfT<java.lang.String> PairOfT<String> worldCup = new PairOfT<String>(2018, "Russia"); PairOfT<String> worldCup = new PairOfT<String>("2018", "Russia");
  • 17. Java => Too much typing
  • 18. Diamond syntax // This program shows the usage of the diamond syntax when using generics class Pair<T1, T2> { T1 object1; T2 object2; Pair(T1 one, T2 two) { object1 = one; object2 = two; } public T1 getFirst() { return object1; } public T2 getSecond() { return object2; } } class TestPair { public static void main(String []args) { Pair<Integer, String> worldCup = new Pair<>(2018, "Russia"); System.out.println("World cup " + worldCup.getFirst() + " in " + worldCup.getSecond()); } } World cup 2018 in Russia
  • 19. Forgetting < and > Pair<Integer, String> worldCup = new Pair(2018, "Russia"); Pair.java:19: warning: [unchecked] unchecked call to Pair(T1,T2) as a member of the raw type Pair Pair<Integer, String> worldCup = new Pair(2018, "Russia"); ^ where T1,T2 are type-variables: T1 extends Object declared in class Pair T2 extends Object declared in class Pair Pair.java:19: warning: [unchecked] unchecked conversion Pair<Integer, String> worldCup = new Pair(2018, "Russia"); ^ required: Pair<Integer,String> found: Pair 2 warnings
  • 20. Type erasure Implementation of generics is static in nature, which means that the Java compiler interprets the generics specified in the source code and replaces the generic code with concrete types. This is referred to as type erasure. After compilation, the code looks similar to what a developer would have written with concrete types.
  • 22. Type erasure T mem = new T(); // wrong usage - compiler error
  • 23. Type erasure T[] amem = new T[100]; // wrong usage - compiler error
  • 24. Type erasure class X<T> { T instanceMem; // okay static T statMem; // wrong usage - compiler error }
  • 25. Generics - limitations You cannot instantiate a generic type with primitive types, for example, List<int> is not allowed. However, you can use boxed primitive types like List<Integer>.
  • 26. Raw types import java.util.List; import java.util.LinkedList; import java.util.Iterator; class RawTest1 { public static void main(String []args) { List list = new LinkedList(); list.add("First"); list.add("Second"); List<String> strList = list; //#1 for(Iterator<String> itemItr = strList.iterator(); itemItr.hasNext();) System.out.println("Item: " + itemItr.next()); List<String> strList2 = new LinkedList<>(); strList2.add("First"); strList2.add("Second"); List list2 = strList2; //#2 for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();) System.out.println("Item: " + itemItr.next()); } } Item: First Item: Second Item: First Item: Second $ javac RawTest1.java Note: RawTest1.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details.
  • 27. Raw types $ javac -Xlint:unchecked RawTest1.java RawTest1.java:14: warning: [unchecked] unchecked call to add(E) as a member of the raw type List list.add("First"); ^ where E is a type-variable: E extends Object declared in interface List RawTest1.java:15: warning: [unchecked] unchecked call to add(E) as a member of the raw type List list.add("Second"); ^ where E is a type-variable: E extends Object declared in interface List RawTest1.java:16: warning: [unchecked] unchecked conversion List<String> strList = list; //#1 ^ required: List<String> found: List RawTest1.java:24: warning: [unchecked] unchecked conversion for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();) ^ required: Iterator<String> found: Iterator 4 warnings $
  • 28. Raw types import java.util.List; import java.util.LinkedList; import java.util.Iterator; class RawTest2 { public static void main(String []args) { List list = new LinkedList(); list.add("First"); list.add("Second"); List<String> strList = list; strList.add(10); // #1: generates compiler error for(Iterator<String> itemItr = strList.iterator(); itemItr.hasNext();) System.out.println("Item : " + itemItr.next()); List<String> strList2 = new LinkedList<>(); strList2.add("First"); strList2.add("Second"); List list2 = strList2; list2.add(10); // #2: compiles fine, results in runtime exception for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();) System.out.println("Item : " + itemItr.next()); } }
  • 29. Raw types List<String> strList2 = new LinkedList<>(); strList2.add("First"); strList2.add("Second"); List list2 = strList2; list2.add(10); // #2: compiles fine, results in runtime exception for(Iterator<String> itemItr = list2.iterator(); itemItr.hasNext();) System.out.println("Item : " + itemItr.next()); Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at RawTest2.main(RawTest2.java:27)
  • 30. Best practice Avoid using raw types of generic types
  • 31. Generic methods // This program demonstrates generic methods import java.util.List; import java.util.ArrayList; class Utilities { public static <T> void fill(List<T> list, T val) { for(int i = 0; i < list.size(); i++) list.set(i, val); } } class UtilitiesTest { public static void main(String []args) { List<Integer> intList = new ArrayList<Integer>(); intList.add(10); intList.add(20); System.out.println("The original list is: " + intList); Utilities.fill(intList, 100); System.out.println("The list after calling Utilities.fill() is: " + intList); } } The original list is: [10, 20] The list after calling Utilities.fill() is: [100, 100]
  • 32. Generics and sub typing Subtyping works for class types: you can assign a derived type object to its base type reference. However, subtyping does not work for generic type parameters: you cannot assign a derived generic type parameter to a base type parameter.
  • 33. Generics and sub typing // illegal code – assume that the following intialization is allowed List<Number> intList = new ArrayList<Integer>(); intList.add(new Integer(10)); // okay intList.add(new Float(10.0f)); // oops!
  • 34. Generics and sub typing List<Number> intList = new ArrayList<Integer>(); WildCardUse.java:6: incompatible types found : java.util.ArrayList<java.lang.Integer> required: java.util.List<java.lang.Number> List<?> wildCardList = new ArrayList<Integer>();
  • 35. Wildcard types Type parameters for generics have a limitation: generic type parameters should match exactly for assignments. To overcome this subtyping problem, you can use wildcard types.
  • 36. Wildcard types Use a wildcard to indicate that it can match for any type: List<?>, you mean that it is a List of any type—in other words, you can say it is a “list of unknowns!
  • 37. How about this “workaround”? WildCardUse.java:6: incompatible types found : java.util.ArrayList<java.lang.Integer> required: java.util.List<java.lang.Object> List<Object> numList = new ArrayList<Integer>(); List<Object> numList = new ArrayList<Integer>();
  • 38. Wildcard use // This program demonstrates the usage of wild card parameters import java.util.List; import java.util.ArrayList; class WildCardUse { static void printList(List<?> list){ for(Object element: list) System.out.println("[" + element + "]"); } public static void main(String []args) { List<Integer> list = new ArrayList<>(); list.add(10); list.add(100); printList(list); List<String> strList = new ArrayList<>(); strList.add("10"); strList.add("100"); printList(strList); } } [10] [100] [10] [100]
  • 39. Limitations of Wildcards List<?> wildCardList = new ArrayList<Integer>(); wildCardList.add(new Integer(10)); System.out.println(wildCardList); WildCardUse.java:7: cannot find symbol symbol : method add(java.lang.Integer) location: interface java.util.List<capture#145 of ? extends java.lang.Number> wildCardList.add(new Integer(10));
  • 40. Wildcard types In general, when you use wildcard parameters, you cannot call methods that modify the object. If youtry to modify, the compiler will give you confusing error messages. However, you can call methods that access the object.
  • 41. More about generics • It’s possible to define or declare generic methods in an interface or a class even if the class or the interface itself is not generic. • A generic class used without type arguments is known as a raw type. Of course, raw types are not type safe. Java supports raw types so that it is possible to use the generic type in code that is older than Java 5 (note that generics were introduced in Java 5). The compiler generates a warning when you use raw types in your code. You may use @SuppressWarnings({ "unchecked" }) to suppress the warning associated with raw types. • List<?> is a supertype of any List type, which means you can pass List<Integer>, or List<String>, or even List<Object> where List<?> is expected.
  • 42. <? super T> and <? extends T> <R> Stream<R> map(Function<? super T,? extends R> transform)
  • 43. Duck<? super Color> or Duck<? extends Color>
  • 44. Generics: Code can be terrible to read
  • 48. Image credits ❖ http://www.ookii.org/misc/cup_of_t.jpg ❖ http://thumbnails-visually.netdna-ssl.com/tea-or-coffee_52612a16dfce8_w1500.png ❖ http://i1.wp.com/limpingchicken.com/wp-content/uploads/2013/04/question-chicken-l.jpg? resize=450%2C232 ❖ https://4.bp.blogspot.com/-knt6r-h4tzE/VvU-7QrZCyI/AAAAAAAAFYs/ welz0JLVgbgOtfRSl98OxztA8Sb4VXxCg/s1600/Generics%2Bin%2BJava.png ❖ http://homepages.inf.ed.ac.uk/wadler/gj/gj-back-full.jpg ❖ http://kaczanowscy.pl/tomek/sites/default/files/generic_monster.jpeg ❖ https://s-media-cache-ak0.pinimg.com/736x/f7/b1/47/f7b147bfbc8332a2e3f2ba3c44a8e6d2.jpg ❖ https://avatars.githubusercontent.com/u/2187012?v=3 ❖ http://image-7.verycd.com/fb2e74a15a36c4e7c1b6d4b1eb148af1104235/lrg.jpg ❖ http://regmedia.co.uk/2007/05/03/cartoon_duck.jpg ❖ https://m.popkey.co/48a22d/VWZR6.gif ❖ http://www.rawstory.com/wp-content/uploads/2012/07/boozehound-shutterstock.jpg ❖ http://www.fantasyfootballgeek.co.uk/wp-content/uploads/2016/04/wildcard-1-1.jpg ❖ https://i.ytimg.com/vi/XB0pGnzsAZI/hqdefault.jpg