SlideShare a Scribd company logo
Java Generics wildcards
Topics
• Wildcards with extends
• E.g. List<? extends Number>
• Wildcards with super
• E.g. List<? super Integer>
• The Get and Put Principle
Wildcards with extends
Wildcards with extends: what is it?
// a List which contains elements whose type is a subtype of Number
List<? extends Number> list_extendsNumber;
// valid:
list_extendsNumber = new ArrayList<Number>();
list_extendsNumber = new ArrayList<Integer>(); // Integer extends Number
list_extendsNumber = new ArrayList<BigDecimal>(); // BigDecimal extends Number
// invalid:
list_extendsNumber = new ArrayList<String>(); // compilation error
// a String is not a Number
list_extendsNumber = new ArrayList<Object>(); // compilation error
// Number extends Object
// but not the other way around
// It's guaranteed that it contains a Number or its subtype
Number firstNumber = list_extendsNumber.get(0);
Wildcards with extends: how can we use it?
// A method which accepts any List whose type parameter is a subtype of Number
double avg(List<? extends Number> nums) {
return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}
// valid:
List<Number> nums = Arrays.asList(1, 0.5d, 3);
assert avg(nums) == 1.5d;
List<Integer> ints = Arrays.asList(1, 2, 3);
assert avg(ints) == 2d;
List<BigDecimal> bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3));
assert avg(bds) == 2d;
// invalid:
List<String> strs = Arrays.asList("foo", "bar", "baz");
avg(strs) // compilation error; a String is not a Number
List<Object> objs = Arrays.asList("foo", 0.5d, 3);
avg(objs) // compilation error; Number extends Object but not the other way around
Wildcards with extends:what’s good about it?
// No wildcard
double avg(List<Number> nums) {
return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0);
}
// valid:
List<Number> nums = Arrays.asList(1, 0.5d, 3);
assert avg(nums) == 1.5d; // still fine
// not valid anymore:
List<Integer> ints = Arrays.asList(1, 2, 3);
assert avg(ints) == 2d; // compilation error
List<BigDecimal> bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3));
assert avg(bds) == 2d; // compilation error
Wildcards with extends provide more flexibility to code which
gets values out of a container object (e.g. List)
Wildcards with extends: limitation
List<? extends Number> list_extendsNumber = new ArrayList<Integer>();
list_extendsNumber.add(null); // compiles; null is the only exception
list_extendsNumber.add(1); // compilation error
// why? remember we can assign the following too
list_extendsNumber = new ArrayList<BigDecimal>(); // it accepts only BigDecimal. not Integer
You won't be able to put any value except for null
through a variable using extends.
Wildcards with super
Wildcards with super: what is it?
// a List which contains elements whose type is a supertype of Integer
List<? super Integer> list_superInteger;
// valid:
list_superInteger = new ArrayList<Integer>();
list_superInteger = new ArrayList<Number>(); // Number is a supertype of Integer
list_superInteger = new ArrayList<Object>(); // Object is a supertype of Integer
// invalid:
list_superInteger = new ArrayList<String>(); // compilation error;
// String is not a supertype of Integer
// It's guaranteed that it can accept an Integer
list_superInteger.put(123);
Wildcards with super: how can we use it?
// A method which accepts any List whose type parameter is a supertype of Integer
void addInts(List<? super Integer> ints) {
Collections.addAll(ints, 1, 2, 3);
}
// valid:
List<Integer> ints = new ArrayList<>();
addInts(ints);
assert ints.toString().equals("[1, 2, 3]");
List<Number> nums = new ArrayList<>();
addInts(nums);
assert nums.toString().equals("[1, 2, 3]");
List<Object> objs = new ArrayList<>();
addInts(objs);
assert objs.toString().equals("[1, 2, 3]");
// invalid:
List<String> strs = new ArrayList<>();
addInts(strs); // compilation error; List<String> cannot accept an Integer
Wildcards with super: what’s good about it?
// No wildcard
void addInts(List<Integer> ints) {
Collections.addAll(ints, 1, 2, 3);
}
// valid:
List<Integer> ints = new ArrayList<>();
addInts(ints);
assert ints.toString().equals("[1, 2, 3]");
// not valid anymore:
List<Number> nums = new ArrayList<>();
addInts(nums); // compilation error
List<Object> objs = new ArrayList<>();
addInts(objs); // compilation error
Wildcards with super provide more flexibility to code which
puts values into a container object (e.g. List).
Wildcards with super: limitation
List<Integer> ints = new ArrayList<>();
ints.add(123);
List<? super Integer> list_superInteger = ints;
Object head = list_superInteger.get(0); // only Object can be used
// as the type of head
assert head.equals(123);
// we cannot do this:
Integer head = list_superInteger.get(0); // compilation error
// why? remember we can assign the following too
list_superInteger = new ArrayList<Object>(); // there is no guarantee that
// it contains an Integer
The only type we can use to get a value out of a variable using super is
the Object type.
The Get and Put Principle
“Use an extends wildcard when you only get values out of a structure,
use a super wildcard when you only put values into a structure, and
don't use a wildcard when you both get and put.”
- Naftalin, M., Wadler, P. (2007). Java Generics And Collections, O'Reilly.
p.19
The Get and Put Principle: an example with
functional interfaces
// Supplier: you only get values out of it
// Consumer: you only put values into it
void myMethod(Supplier<? extends Number> numberSupplier, Consumer<? super String> stringConsumer) {
Number number = numberSupplier.get();
String result = "I got a number whose value in double is: " + number.doubleValue();
stringConsumer.accept(result);
}
// client code: parameters don’t necessarily have to be Supplier<Number> and Consumer<String>
Supplier<BigDecimal> bigDecimalSupplier = () -> new BigDecimal("0.5");
AtomicReference<Object> reference = new AtomicReference<>();
Consumer<Object> objectConsumer = reference::set;
myMethod(bigDecimalSupplier, objectConsumer);
assert reference.get().equals("I got a number whose value in double is: 0.5");
Conclusion
• We’ve discussed the following topics about Generics wildcards:
• Usage
• Benefits
• Limitations
• When to use
• Java Generics wildcards make Java code more flexible and type-safe.
• When you write a method or a constructor which receives an object
that has a type parameter, think if you can apply one.

More Related Content

What's hot

C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
MohitKumar1985
 
SQL Prepared Statements Tutorial
SQL Prepared Statements TutorialSQL Prepared Statements Tutorial
SQL Prepared Statements Tutorial
ProdigyView
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
kumar gaurav
 
Types of Arrays
Types of ArraysTypes of Arrays
Types of Arrays
Ans Ali
 
Chapter 6 java
Chapter 6 javaChapter 6 java
Chapter 6 java
Ahmad sohail Kakar
 
CPP05 - Arrays
CPP05 - ArraysCPP05 - Arrays
CPP05 - Arrays
Michael Heron
 
Python set
Python setPython set
Python set
Mohammed Sikander
 
Lists in Python
Lists in PythonLists in Python
Lists in Python
Md. Shafiuzzaman Hira
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
yugandhar vadlamudi
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
Data area interaction using rpg
Data area interaction using rpgData area interaction using rpg
Data area interaction using rpg
swarupchoudhuri
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
michael.labriola
 
List Manipulation in FME
List Manipulation in FMEList Manipulation in FME
List Manipulation in FME
Safe Software
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Php, mysqlpart2
Php, mysqlpart2Php, mysqlpart2
Php, mysqlpart2
Subhasis Nayak
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
Drishti Bhalla
 
Arrays and linked lists
Arrays and linked listsArrays and linked lists
Arrays and linked lists
AfriyieCharles
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]
Somkiat Khitwongwattana
 

What's hot (19)

C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 
SQL Prepared Statements Tutorial
SQL Prepared Statements TutorialSQL Prepared Statements Tutorial
SQL Prepared Statements Tutorial
 
Java collections concept
Java collections conceptJava collections concept
Java collections concept
 
Types of Arrays
Types of ArraysTypes of Arrays
Types of Arrays
 
Chapter 6 java
Chapter 6 javaChapter 6 java
Chapter 6 java
 
CPP05 - Arrays
CPP05 - ArraysCPP05 - Arrays
CPP05 - Arrays
 
Python set
Python setPython set
Python set
 
Lists in Python
Lists in PythonLists in Python
Lists in Python
 
Collections framework in java
Collections framework in javaCollections framework in java
Collections framework in java
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
 
Data area interaction using rpg
Data area interaction using rpgData area interaction using rpg
Data area interaction using rpg
 
Any Which Array But Loose
Any Which Array But LooseAny Which Array But Loose
Any Which Array But Loose
 
List Manipulation in FME
List Manipulation in FMEList Manipulation in FME
List Manipulation in FME
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Php, mysqlpart2
Php, mysqlpart2Php, mysqlpart2
Php, mysqlpart2
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Arrays and linked lists
Arrays and linked listsArrays and linked lists
Arrays and linked lists
 
ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]ListView and Custom ListView on Android Development [Thai]
ListView and Custom ListView on Android Development [Thai]
 

Similar to Java Generics wildcards

Given the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdfGiven the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdf
NicholasflqStewartl
 
Applying Generics
Applying GenericsApplying Generics
Applying Generics
Bharat17485
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
alanfhall8953
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
firstchoiceajmer
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
adinathassociates
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
ANUSUYA S
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
sotlsoc
 
Write a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdfWrite a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdf
ebrahimbadushata00
 
12. arrays
12. arrays12. arrays
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
Ahsanul Karim
 
Java Generics
Java GenericsJava Generics
Java Generics
Zülfikar Karakaya
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdf
fonecomp
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
TaseerRao
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
valerie5142000
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
ansariparveen06
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
AqeelAbbas94
 
array Details
array Detailsarray Details
array Details
shivas379526
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
info335653
 

Similar to Java Generics wildcards (20)

Given the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdfGiven the following errors and class in Java- How are these errors fix.pdf
Given the following errors and class in Java- How are these errors fix.pdf
 
Applying Generics
Applying GenericsApplying Generics
Applying Generics
 
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docxweek4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
week4_srcArrayMethods.javaweek4_srcArrayMethods.javapackage ed.docx
 
Everything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdfEverything needs to be according to the instructions- thank you! SUPPO.pdf
Everything needs to be according to the instructions- thank you! SUPPO.pdf
 
java I am trying to run my code but it is not letting me .pdf
java    I am trying to run my code but it is not letting me .pdfjava    I am trying to run my code but it is not letting me .pdf
java I am trying to run my code but it is not letting me .pdf
 
C++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about PointersC++ - UNIT_-_IV.pptx which contains details about Pointers
C++ - UNIT_-_IV.pptx which contains details about Pointers
 
Chapter 7.1
Chapter 7.1Chapter 7.1
Chapter 7.1
 
Write a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdfWrite a java class LIST that outputsmainpublic class Ass.pdf
Write a java class LIST that outputsmainpublic class Ass.pdf
 
12. arrays
12. arrays12. arrays
12. arrays
 
Day 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViewsDay 8: Dealing with Lists and ListViews
Day 8: Dealing with Lists and ListViews
 
Java Generics
Java GenericsJava Generics
Java Generics
 
I need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdfI need help with this program for java.The program you are given t.pdf
I need help with this program for java.The program you are given t.pdf
 
Arrays in programming
Arrays in programmingArrays in programming
Arrays in programming
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
ch06.ppt
ch06.pptch06.ppt
ch06.ppt
 
array Details
array Detailsarray Details
array Details
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
 
you will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdfyou will implement some sorting algorithms for arrays and linked lis.pdf
you will implement some sorting algorithms for arrays and linked lis.pdf
 

More from Kohei Nozaki

The State Pattern
The State PatternThe State Pattern
The State Pattern
Kohei Nozaki
 
Synchronize access to shared mutable data
Synchronize access to shared mutable dataSynchronize access to shared mutable data
Synchronize access to shared mutable data
Kohei Nozaki
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In Java
Kohei Nozaki
 
Favor composition over inheritance
Favor composition over inheritanceFavor composition over inheritance
Favor composition over inheritance
Kohei Nozaki
 
JUnit and Mockito tips
JUnit and Mockito tipsJUnit and Mockito tips
JUnit and Mockito tips
Kohei Nozaki
 
Overview of Java EE
Overview of Java EEOverview of Java EE
Overview of Java EE
Kohei Nozaki
 

More from Kohei Nozaki (6)

The State Pattern
The State PatternThe State Pattern
The State Pattern
 
Synchronize access to shared mutable data
Synchronize access to shared mutable dataSynchronize access to shared mutable data
Synchronize access to shared mutable data
 
The Singleton Pattern In Java
The Singleton Pattern In JavaThe Singleton Pattern In Java
The Singleton Pattern In Java
 
Favor composition over inheritance
Favor composition over inheritanceFavor composition over inheritance
Favor composition over inheritance
 
JUnit and Mockito tips
JUnit and Mockito tipsJUnit and Mockito tips
JUnit and Mockito tips
 
Overview of Java EE
Overview of Java EEOverview of Java EE
Overview of Java EE
 

Recently uploaded

在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
mz5nrf0n
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
VALiNTRY360
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
Peter Muessig
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
kalichargn70th171
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
Philip Schwarz
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
Peter Muessig
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
sjcobrien
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
TaghreedAltamimi
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
Marcin Chrost
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
mz5nrf0n
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
Green Software Development
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
dakas1
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
kalichargn70th171
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
Rakesh Kumar R
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
GohKiangHock
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
Green Software Development
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
Drona Infotech
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
AnkitaPandya11
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
Rakesh Kumar R
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
Octavian Nadolu
 

Recently uploaded (20)

在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
在线购买加拿大英属哥伦比亚大学毕业证本科学位证书原版一模一样
 
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdfTop Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
Top Benefits of Using Salesforce Healthcare CRM for Patient Management.pdf
 
UI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design SystemUI5con 2024 - Bring Your Own Design System
UI5con 2024 - Bring Your Own Design System
 
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
The Key to Digital Success_ A Comprehensive Guide to Continuous Testing Integ...
 
Hand Rolled Applicative User Validation Code Kata
Hand Rolled Applicative User ValidationCode KataHand Rolled Applicative User ValidationCode Kata
Hand Rolled Applicative User Validation Code Kata
 
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s EcosystemUI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
UI5con 2024 - Keynote: Latest News about UI5 and it’s Ecosystem
 
Malibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed RoundMalibou Pitch Deck For Its €3M Seed Round
Malibou Pitch Deck For Its €3M Seed Round
 
Lecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptxLecture 2 - software testing SE 412.pptx
Lecture 2 - software testing SE 412.pptx
 
Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !Enums On Steroids - let's look at sealed classes !
Enums On Steroids - let's look at sealed classes !
 
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
原版定制美国纽约州立大学奥尔巴尼分校毕业证学位证书原版一模一样
 
GreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-JurisicGreenCode-A-VSCode-Plugin--Dario-Jurisic
GreenCode-A-VSCode-Plugin--Dario-Jurisic
 
一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理一比一原版(USF毕业证)旧金山大学毕业证如何办理
一比一原版(USF毕业证)旧金山大学毕业证如何办理
 
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf8 Best Automated Android App Testing Tool and Framework in 2024.pdf
8 Best Automated Android App Testing Tool and Framework in 2024.pdf
 
Fundamentals of Programming and Language Processors
Fundamentals of Programming and Language ProcessorsFundamentals of Programming and Language Processors
Fundamentals of Programming and Language Processors
 
SQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure MalaysiaSQL Accounting Software Brochure Malaysia
SQL Accounting Software Brochure Malaysia
 
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, FactsALGIT - Assembly Line for Green IT - Numbers, Data, Facts
ALGIT - Assembly Line for Green IT - Numbers, Data, Facts
 
Mobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona InfotechMobile App Development Company In Noida | Drona Infotech
Mobile App Development Company In Noida | Drona Infotech
 
fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.fiscal year variant fiscal year variant.
fiscal year variant fiscal year variant.
 
How to write a program in any programming language
How to write a program in any programming languageHow to write a program in any programming language
How to write a program in any programming language
 
Artificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension FunctionsArtificia Intellicence and XPath Extension Functions
Artificia Intellicence and XPath Extension Functions
 

Java Generics wildcards

  • 2. Topics • Wildcards with extends • E.g. List<? extends Number> • Wildcards with super • E.g. List<? super Integer> • The Get and Put Principle
  • 4. Wildcards with extends: what is it? // a List which contains elements whose type is a subtype of Number List<? extends Number> list_extendsNumber; // valid: list_extendsNumber = new ArrayList<Number>(); list_extendsNumber = new ArrayList<Integer>(); // Integer extends Number list_extendsNumber = new ArrayList<BigDecimal>(); // BigDecimal extends Number // invalid: list_extendsNumber = new ArrayList<String>(); // compilation error // a String is not a Number list_extendsNumber = new ArrayList<Object>(); // compilation error // Number extends Object // but not the other way around // It's guaranteed that it contains a Number or its subtype Number firstNumber = list_extendsNumber.get(0);
  • 5. Wildcards with extends: how can we use it? // A method which accepts any List whose type parameter is a subtype of Number double avg(List<? extends Number> nums) { return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0); } // valid: List<Number> nums = Arrays.asList(1, 0.5d, 3); assert avg(nums) == 1.5d; List<Integer> ints = Arrays.asList(1, 2, 3); assert avg(ints) == 2d; List<BigDecimal> bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)); assert avg(bds) == 2d; // invalid: List<String> strs = Arrays.asList("foo", "bar", "baz"); avg(strs) // compilation error; a String is not a Number List<Object> objs = Arrays.asList("foo", 0.5d, 3); avg(objs) // compilation error; Number extends Object but not the other way around
  • 6. Wildcards with extends:what’s good about it? // No wildcard double avg(List<Number> nums) { return nums.stream().mapToDouble(Number::doubleValue).average().orElse(0); } // valid: List<Number> nums = Arrays.asList(1, 0.5d, 3); assert avg(nums) == 1.5d; // still fine // not valid anymore: List<Integer> ints = Arrays.asList(1, 2, 3); assert avg(ints) == 2d; // compilation error List<BigDecimal> bds = Arrays.asList(new BigDecimal(1), new BigDecimal(2), new BigDecimal(3)); assert avg(bds) == 2d; // compilation error Wildcards with extends provide more flexibility to code which gets values out of a container object (e.g. List)
  • 7. Wildcards with extends: limitation List<? extends Number> list_extendsNumber = new ArrayList<Integer>(); list_extendsNumber.add(null); // compiles; null is the only exception list_extendsNumber.add(1); // compilation error // why? remember we can assign the following too list_extendsNumber = new ArrayList<BigDecimal>(); // it accepts only BigDecimal. not Integer You won't be able to put any value except for null through a variable using extends.
  • 9. Wildcards with super: what is it? // a List which contains elements whose type is a supertype of Integer List<? super Integer> list_superInteger; // valid: list_superInteger = new ArrayList<Integer>(); list_superInteger = new ArrayList<Number>(); // Number is a supertype of Integer list_superInteger = new ArrayList<Object>(); // Object is a supertype of Integer // invalid: list_superInteger = new ArrayList<String>(); // compilation error; // String is not a supertype of Integer // It's guaranteed that it can accept an Integer list_superInteger.put(123);
  • 10. Wildcards with super: how can we use it? // A method which accepts any List whose type parameter is a supertype of Integer void addInts(List<? super Integer> ints) { Collections.addAll(ints, 1, 2, 3); } // valid: List<Integer> ints = new ArrayList<>(); addInts(ints); assert ints.toString().equals("[1, 2, 3]"); List<Number> nums = new ArrayList<>(); addInts(nums); assert nums.toString().equals("[1, 2, 3]"); List<Object> objs = new ArrayList<>(); addInts(objs); assert objs.toString().equals("[1, 2, 3]"); // invalid: List<String> strs = new ArrayList<>(); addInts(strs); // compilation error; List<String> cannot accept an Integer
  • 11. Wildcards with super: what’s good about it? // No wildcard void addInts(List<Integer> ints) { Collections.addAll(ints, 1, 2, 3); } // valid: List<Integer> ints = new ArrayList<>(); addInts(ints); assert ints.toString().equals("[1, 2, 3]"); // not valid anymore: List<Number> nums = new ArrayList<>(); addInts(nums); // compilation error List<Object> objs = new ArrayList<>(); addInts(objs); // compilation error Wildcards with super provide more flexibility to code which puts values into a container object (e.g. List).
  • 12. Wildcards with super: limitation List<Integer> ints = new ArrayList<>(); ints.add(123); List<? super Integer> list_superInteger = ints; Object head = list_superInteger.get(0); // only Object can be used // as the type of head assert head.equals(123); // we cannot do this: Integer head = list_superInteger.get(0); // compilation error // why? remember we can assign the following too list_superInteger = new ArrayList<Object>(); // there is no guarantee that // it contains an Integer The only type we can use to get a value out of a variable using super is the Object type.
  • 13. The Get and Put Principle “Use an extends wildcard when you only get values out of a structure, use a super wildcard when you only put values into a structure, and don't use a wildcard when you both get and put.” - Naftalin, M., Wadler, P. (2007). Java Generics And Collections, O'Reilly. p.19
  • 14. The Get and Put Principle: an example with functional interfaces // Supplier: you only get values out of it // Consumer: you only put values into it void myMethod(Supplier<? extends Number> numberSupplier, Consumer<? super String> stringConsumer) { Number number = numberSupplier.get(); String result = "I got a number whose value in double is: " + number.doubleValue(); stringConsumer.accept(result); } // client code: parameters don’t necessarily have to be Supplier<Number> and Consumer<String> Supplier<BigDecimal> bigDecimalSupplier = () -> new BigDecimal("0.5"); AtomicReference<Object> reference = new AtomicReference<>(); Consumer<Object> objectConsumer = reference::set; myMethod(bigDecimalSupplier, objectConsumer); assert reference.get().equals("I got a number whose value in double is: 0.5");
  • 15. Conclusion • We’ve discussed the following topics about Generics wildcards: • Usage • Benefits • Limitations • When to use • Java Generics wildcards make Java code more flexible and type-safe. • When you write a method or a constructor which receives an object that has a type parameter, think if you can apply one.