SlideShare a Scribd company logo
1 of 49
Download to read offline
JAVA GENERICS: BY EXAMPLE
ganesh@codeops.tech
Ganesh Samarthyam
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

What's hot

Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
Pramod Kumar
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
Soumya Behera
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
Mario Fusco
 

What's hot (19)

Why Learn Python?
Why Learn Python?Why Learn Python?
Why Learn Python?
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
Scalaz By Example (An IO Taster) -- PDXScala Meetup Jan 2014
 
Java Generics for Dummies
Java Generics for DummiesJava Generics for Dummies
Java Generics for Dummies
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 
Java programs
Java programsJava programs
Java programs
 
Unit testing concurrent code
Unit testing concurrent codeUnit testing concurrent code
Unit testing concurrent code
 
Java practical
Java practicalJava practical
Java practical
 
Java Generics
Java GenericsJava Generics
Java Generics
 
java sockets
 java sockets java sockets
java sockets
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Java 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forwardJava 7, 8 & 9 - Moving the language forward
Java 7, 8 & 9 - Moving the language forward
 
Initial Java Core Concept
Initial Java Core ConceptInitial Java Core Concept
Initial Java Core Concept
 
OOP Core Concept
OOP Core ConceptOOP Core Concept
OOP Core Concept
 

Viewers also liked

Viewers also liked (8)

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

Similar to Java Generics - by Example

Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
Eelco Visser
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
aromanets
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
imypraz
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
Rakesh Madugula
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
trixiacruz
 

Similar to Java Generics - by Example (20)

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)
 
Java generics
Java genericsJava generics
Java generics
 
Writing beautiful code with Java 8
Writing beautiful code with Java 8Writing beautiful code with Java 8
Writing beautiful code with Java 8
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Lecture 5: Functional Programming
Lecture 5: Functional ProgrammingLecture 5: Functional Programming
Lecture 5: Functional Programming
 
Icom4015 lecture15-f16
Icom4015 lecture15-f16Icom4015 lecture15-f16
Icom4015 lecture15-f16
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Xebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_finalXebicon2013 scala vsjava_final
Xebicon2013 scala vsjava_final
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Csharp4 generics
Csharp4 genericsCsharp4 generics
Csharp4 generics
 
Jdk1.5 Features
Jdk1.5 FeaturesJdk1.5 Features
Jdk1.5 Features
 
Java New Programming Features
Java New Programming FeaturesJava New Programming Features
Java New Programming Features
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Java8: Language Enhancements
Java8: Language EnhancementsJava8: Language Enhancements
Java8: Language Enhancements
 
Java 8 Workshop
Java 8 WorkshopJava 8 Workshop
Java 8 Workshop
 
Collections
CollectionsCollections
Collections
 
New features and enhancement
New features and enhancementNew features and enhancement
New features and enhancement
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
3 functions and class
3   functions and class3   functions and class
3 functions and class
 
Scala cheatsheet
Scala cheatsheetScala cheatsheet
Scala cheatsheet
 

More from Ganesh Samarthyam

More from Ganesh Samarthyam (20)

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

Recently uploaded

+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Recently uploaded (20)

BUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptxBUS PASS MANGEMENT SYSTEM USING PHP.pptx
BUS PASS MANGEMENT SYSTEM USING PHP.pptx
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 

Java Generics - by Example

  • 1. JAVA GENERICS: BY EXAMPLE ganesh@codeops.tech Ganesh Samarthyam
  • 2.
  • 3.
  • 4.
  • 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