SlideShare a Scribd company logo
Java Generics
Zülfikar Karakaya
Agenda
• History
• Terms
• Erasure-Reification-Subtyping
• Generification
• Generic Methods (Get and Put Principal)
• Wildcards in Detail
History
Java supports generics as of version 1.5
Before
list of integers List
list of strings List
list of lists of strings List
After
list of integers List<Integer>
list of strings List<String>
list of lists of strings List<List<String>>
«Now compiler can track what we have list of»
Terms
Term Example
Parameterized type List<String>
Actual type parameter String
Generic type List<E>
Formal type parameter E
Unbounded wildcard type List<?>
Raw type List
Bounded type parameter <E extends Number>
Recursive type bound <T extends Comparable<T>>
Bounded wildcard type List<? extends Number>
Generic method static <E> List<E> asList (E[] a)
Type token List.class
Before-after generics
// before generics
List words = new ArrayList();
words.add("Hello ");
words.add("world!");
String s = ((String)words.get(0))+((String)words.get(1))
assert s.equals("Hello world!");
// with generics
List<String> words = new ArrayList<String>();
words.add("Hello ");
words.add("world!");
String s = words.get(0)+words.get(1); // no explicit casts
assert s.equals("Hello world!");
«since generics are implemented by erasure
at bytecode level, two sources above will be identical»
Use raw types in..
class literals
List.class // legal
String[].class // legal
int.class // legal
List<String>.class // illegal since erasure
List<?>.class // illegal
instanceof operator
if (o instanceof Set) {
Set<?> set = (Set<?>) o; // checked cast, no warning
}
Reification
// allocates an array that its components are type of String,
// so we say that it is reified
String[] aStringArray = new String[10];
// allocates a list with no type information,
// Java does not reify generic types
List<String> aStringList = new ArrayList<String>();
Comparing List, List<?>, List<Object>
List unboundedList = new ArrayList<Integer>();
// legal (warning)
List<?> unboundedList = new ArrayList<Integer>();
// legal, partial type-safe
List<?> unboundedList = new ArrayList<?>();
// illegal
List<Object> unboundedList = new ArrayList<Integer>();
// illegal, invariant
« List<sub> is not a subtype of List<super> »
What is the difference?
static int countCommonElements(Set s1, Set s2) {
int result = 0;
for (Object o1 : s1) {
if (s2.contains( o1 ))
result++;
}
return result;
}
static int countCommonElements(Set<?> s1, Set<?> s2) {
int result = 0;
for (Object o1 : s1) {
if (s2.contains( o1 ))
result++;
}
return result;
}
Arrays
« sub[] is a subtype of super[], so its covariant »
Object[] anObjectArray = new Integer[10];
// legal, covariant
anObjectArray[0] = new String("abc");
// no type safety, causes runtime exception
// like arrays, raw collection types arent’n type-safe
List list = new ArrayList();
list.add("one");
list.add(new Integer(1));
String s = (String) list.get(1); // ClassCastException
Boxing-Unboxing
public static int sum (List<Integer> ints) {
int s = 0;
for (int n : ints) { s += n; }
return s;
}
public static Integer sumInteger(List<Integer> ints) {
Integer s = 0;
for (Integer n : ints) { s += n; }
return s;
}
public class Stack {
private Object[] stack;
private int top = 0;
private static final int INITIAL_CAPACITY = 8;
public Stack() {
stack = new Object[INITIAL_CAPACITY];
}
public void push(Object obj) {
ensureCapacity();
stack[top++] = obj;
}
public Object pop() {
if (top == 0) // stack is empty
throw new EmptyStackException();
Object temp = stack[--top];
stack[top]=null;
return temp;
}
public boolean isEmpty(){
return top == 0;
}
public void ensureCapacity() {
if (stack.length == top)
stack = Arrays.copyOf(stack, 2 * top + 1);
}
}
public class GenericStack<E> {
private E[] stack;
private int top = 0;
private static final int INITIAL_CAPACITY = 8;
@SuppressWarnings( "unchecked" )
public GenericStack() {
stack = (E[]) new Object[INITIAL_CAPACITY];
}
public void push(E obj) {
ensureCapacity();
stack[top++] = obj;
}
public E pop() {
if (top == 0) // stack is empty
return null;
E temp = stack[--top];
stack[top]=null;
return temp;
}
public boolean isEmpty(){
return top == 0;
}
public void ensureCapacity() {
if (stack.length == top)
stack = Arrays.copyOf(stack, 2 * top + 1);
}
}
Generify legacy codes
Generic methods
public static <E> Set<E> union (Set<E> s1, Set<E> s2)
«Static utility methods are good candidates for generification »
formal type parameter
return type
type parameter
Get and Put Principal
// PECS (producer extends, consumer super) principal
public static <T> void copy(
List<? super T> dst, List<? extends T> src ) {
for ( int i = 0; i < src.size(); i++ ) {
dst.set( i, src.get( i ) );
}
}
// usage
List<Object> objs = Arrays.<Object>asList(2, 3.14, "four");
List<Integer> ints = Arrays.asList(5, 6);
Collections.copy(objs, ints); // type inference
assert objs.toString().equals("[5, 6, four]");
Copy method (alternatives)
public static <T> void copy(
List<T> dst, List<T> src);
public static <T> void copy(
List<T> dst, List<? extends T> src);
public static <T> void copy(
List<? super T> dst, List<T> src);
public static <T> void copy(
List<? super T> dst, List<? extends T> src);
Comparables
public static <T extends Comparable<T>> T max (
List<T> list);
« All comparables and comparators are consumers »
public static <T extends Comparable<? super T>> T max(
List<? extends T> list);
Tips on wildcard types
«Use wildcard types on input parameters
for maximum flexibility»
«Do not use a wildcard for an input
parameter if you both get and put on that
parameter»
« Do not use wildcard types as return
types »
Restrictions on Wildcards
Instance Creation
List<?> list = new ArrayList<?>(); // illegal
List<List<?>> lists = new ArrayList<List<?>>(); // legal
lists.add(Arrays.asList(1,2,3));
lists.add(Arrays.asList("four","five"));
Generic Method Calls
List<?> list = Lists.<?>factory(); // illegal
List<List<?>> list = Lists.<List<?>>factory(); // legal
Supertypes
class AnyList extends ArrayList<?> {...} // illegal
Wildcard capturing
public static <T> void reverse(List<T> list) {
List<T> tmp = new ArrayList<T>(list);
for (int i = 0; i < list.size(); i++) {
list.set(i, tmp.get(list.size() - i - 1));
}
}
public static void reverse(List<?> list) {
List<Object> tmp = new ArrayList<Object>(list);
for (int i = 0; i < list.size(); i++) {
list.set(i, tmp.get(list.size() - i - 1)); // error
}
}
Wildcard capturing (continue)
public static void reverse(List<?> list) {
rev(list);
}
private static <T> void rev(List<T> list) {
List<T> tmp = new ArrayList<T>(list);
for (int i = 0; i < list.size(); i++) {
list.set(i, tmp.get(list.size() - i - 1));
}
}
« Here we say that the type variable T has captured the wildcard. This is a
generally useful technique when dealing with wildcards,
and it is worth knowing. »
Use Checked Collections to Enforce Security
private class Order { }
private class AuthenticatedOrder extends Order { }
..
List<AuthenticatedOrder> checkedList =
new ArrayList<AuthenticatedOrder>();
addChecked(Collections.checkedList(
checkedList, AuthenticatedOrder.class));
..
public void addChecked(List<AuthenticatedOrder> checkedList) {
List raw = checkedList;
Order order = new Order();
raw.add(order); // unchecked call, ClassCastException at runtime
}
References
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html
Angelika Langer
Effective Java
Joshua Bloch
Java Generics and Collections
Maurice Naftalin and Philip Wadler
Java Generics
Zülfikar Karakaya
Ad

More Related Content

What's hot (20)

Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
Jason Myers
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
Vladislav sidlyarevich
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
ICS
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
Ramakrishna Joshi
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Java script basics
Java script basicsJava script basics
Java script basics
Shrivardhan Limbkar
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQL
Norvald Ryeng
 
Python my sql database connection
Python my sql   database connectionPython my sql   database connection
Python my sql database connection
Learnbay Datascience
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
Scott Leberknight
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
anshu_atri
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Introduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORMIntroduction to SQLAlchemy ORM
Introduction to SQLAlchemy ORM
Jason Myers
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
VMware Tanzu
 
QVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI developmentQVariant, QObject — Qt's not just for GUI development
QVariant, QObject — Qt's not just for GUI development
ICS
 
How Hashmap works internally in java
How Hashmap works internally  in javaHow Hashmap works internally  in java
How Hashmap works internally in java
Ramakrishna Joshi
 
JavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQueryJavaScript Fundamentals & JQuery
JavaScript Fundamentals & JQuery
Jamshid Hashimi
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
PHP Form Validation Technique
PHP Form Validation TechniquePHP Form Validation Technique
PHP Form Validation Technique
Morshedul Arefin
 
JSON Array Indexes in MySQL
JSON Array Indexes in MySQLJSON Array Indexes in MySQL
JSON Array Indexes in MySQL
Norvald Ryeng
 
Java Serialization
Java SerializationJava Serialization
Java Serialization
imypraz
 
Introduction to web programming with JavaScript
Introduction to web programming with JavaScriptIntroduction to web programming with JavaScript
Introduction to web programming with JavaScript
T11 Sessions
 
5 collection framework
5 collection framework5 collection framework
5 collection framework
Minal Maniar
 
Collections - Array List
Collections - Array List Collections - Array List
Collections - Array List
Hitesh-Java
 
Generic programming in java
Generic programming in javaGeneric programming in java
Generic programming in java
anshu_atri
 
SQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTIONSQL BUILT-IN FUNCTION
SQL BUILT-IN FUNCTION
Arun Sial
 

Viewers also liked (10)

Interfaces en java
Interfaces en javaInterfaces en java
Interfaces en java
Daniiel Toorres
 
Clases abstractas e interfaces en java
Clases abstractas e interfaces en javaClases abstractas e interfaces en java
Clases abstractas e interfaces en java
Juan Carlos Almeida Mera
 
Interfaces en Java
Interfaces en JavaInterfaces en Java
Interfaces en Java
Humberto Chalate Jorge
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
jehan1987
 
POO - 17 - Interfaces
POO - 17 - InterfacesPOO - 17 - Interfaces
POO - 17 - Interfaces
Ludimila Monjardim Casagrande
 
Poo Java
Poo JavaPoo Java
Poo Java
eccutpl
 
¿Qué es una interface en java?
¿Qué es una interface en java?¿Qué es una interface en java?
¿Qué es una interface en java?
Erick Aguila Martínez
 
Interfaces en Java
Interfaces en JavaInterfaces en Java
Interfaces en Java
Alejandro Miguel
 
Clases abstractas e interfaces
Clases abstractas e interfacesClases abstractas e interfaces
Clases abstractas e interfaces
lopezcortes
 
Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Ad

Similar to Java Generics (20)

ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
 ReverseList.javaimport java.util.ArrayList;public class Rever.pdf ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
aryan9007
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
David Pollak
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
BG Java EE Course
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
JDK 8
JDK 8JDK 8
JDK 8
Maciej Dragan
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
arpaqindia
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docx
Stewartt0kJohnstonh
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
Array list
Array listArray list
Array list
vishal choudhary
 
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
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
PathOfMostResistance
PathOfMostResistancePathOfMostResistance
PathOfMostResistance
Edward Cleveland
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Henri Tremblay
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
 ReverseList.javaimport java.util.ArrayList;public class Rever.pdf ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
ReverseList.javaimport java.util.ArrayList;public class Rever.pdf
aryan9007
 
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdfLabprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
Labprogram.javaLinkedList.javaimport java.util.NoSuchElementEx.pdf
freddysarabia1
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
Joni
 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
DEVTYPE
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
David Pollak
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdfJAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
JAVALAB #8 - ARRAY BASED LISTSThe next exercise is based on this.pdf
arpaqindia
 
Please add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docxPlease add-modify the following to the original code using C# 1- Delet.docx
Please add-modify the following to the original code using C# 1- Delet.docx
Stewartt0kJohnstonh
 
16 Linear data structures
16 Linear data structures16 Linear data structures
16 Linear data structures
maznabili
 
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
 
ReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdfReversePoem.java ---------------------------------- public cl.pdf
ReversePoem.java ---------------------------------- public cl.pdf
ravikapoorindia
 
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup GroupJava 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Java 8, lambdas, generics: How to survive? - NYC Java Meetup Group
Henri Tremblay
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
amazing2001
 
Kotlin collections
Kotlin collectionsKotlin collections
Kotlin collections
Myeongin Woo
 
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdfPLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
PLEASE MAKE SURE THE PROGRAM IS ASKING FOR INPUT FROM USER TO ADD OR.pdf
mallik3000
 
Ad

Recently uploaded (20)

Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 
Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025Adobe After Effects Crack FREE FRESH version 2025
Adobe After Effects Crack FREE FRESH version 2025
kashifyounis067
 
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Exceptional Behaviors: How Frequently Are They Tested? (AST 2025)
Andre Hora
 
FL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full VersionFL Studio Producer Edition Crack 2025 Full Version
FL Studio Producer Edition Crack 2025 Full Version
tahirabibi60507
 
How to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud PerformanceHow to Optimize Your AWS Environment for Improved Cloud Performance
How to Optimize Your AWS Environment for Improved Cloud Performance
ThousandEyes
 
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdfMicrosoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
Microsoft AI Nonprofit Use Cases and Live Demo_2025.04.30.pdf
TechSoup
 
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
How to Batch Export Lotus Notes NSF Emails to Outlook PST Easily?
steaveroggers
 
Douwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License codeDouwan Crack 2025 new verson+ License code
Douwan Crack 2025 new verson+ License code
aneelaramzan63
 
PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025PDF Reader Pro Crack Latest Version FREE Download 2025
PDF Reader Pro Crack Latest Version FREE Download 2025
mu394968
 
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Salesforce Data Cloud- Hyperscale data platform, built for Salesforce.
Dele Amefo
 
Maxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINKMaxon CINEMA 4D 2025 Crack FREE Download LINK
Maxon CINEMA 4D 2025 Crack FREE Download LINK
younisnoman75
 
Download Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With LatestDownload Wondershare Filmora Crack [2025] With Latest
Download Wondershare Filmora Crack [2025] With Latest
tahirabibi60507
 
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New VersionPixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
Pixologic ZBrush Crack Plus Activation Key [Latest 2025] New Version
saimabibi60507
 
Top 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docxTop 10 Client Portal Software Solutions for 2025.docx
Top 10 Client Portal Software Solutions for 2025.docx
Portli
 
Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]Get & Download Wondershare Filmora Crack Latest [2025]
Get & Download Wondershare Filmora Crack Latest [2025]
saniaaftab72555
 
Landscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature ReviewLandscape of Requirements Engineering for/by AI through Literature Review
Landscape of Requirements Engineering for/by AI through Literature Review
Hironori Washizaki
 
Exploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the FutureExploring Wayland: A Modern Display Server for the Future
Exploring Wayland: A Modern Display Server for the Future
ICS
 
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Mastering Fluent Bit: Ultimate Guide to Integrating Telemetry Pipelines with ...
Eric D. Schabell
 
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
How Valletta helped healthcare SaaS to transform QA and compliance to grow wi...
Egor Kaleynik
 
Societal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainabilitySocietal challenges of AI: biases, multilinguism and sustainability
Societal challenges of AI: biases, multilinguism and sustainability
Jordi Cabot
 
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and CollaborateMeet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Meet the Agents: How AI Is Learning to Think, Plan, and Collaborate
Maxim Salnikov
 

Java Generics

  • 2. Agenda • History • Terms • Erasure-Reification-Subtyping • Generification • Generic Methods (Get and Put Principal) • Wildcards in Detail
  • 3. History Java supports generics as of version 1.5 Before list of integers List list of strings List list of lists of strings List After list of integers List<Integer> list of strings List<String> list of lists of strings List<List<String>> «Now compiler can track what we have list of»
  • 4. Terms Term Example Parameterized type List<String> Actual type parameter String Generic type List<E> Formal type parameter E Unbounded wildcard type List<?> Raw type List Bounded type parameter <E extends Number> Recursive type bound <T extends Comparable<T>> Bounded wildcard type List<? extends Number> Generic method static <E> List<E> asList (E[] a) Type token List.class
  • 5. Before-after generics // before generics List words = new ArrayList(); words.add("Hello "); words.add("world!"); String s = ((String)words.get(0))+((String)words.get(1)) assert s.equals("Hello world!"); // with generics List<String> words = new ArrayList<String>(); words.add("Hello "); words.add("world!"); String s = words.get(0)+words.get(1); // no explicit casts assert s.equals("Hello world!"); «since generics are implemented by erasure at bytecode level, two sources above will be identical»
  • 6. Use raw types in.. class literals List.class // legal String[].class // legal int.class // legal List<String>.class // illegal since erasure List<?>.class // illegal instanceof operator if (o instanceof Set) { Set<?> set = (Set<?>) o; // checked cast, no warning }
  • 7. Reification // allocates an array that its components are type of String, // so we say that it is reified String[] aStringArray = new String[10]; // allocates a list with no type information, // Java does not reify generic types List<String> aStringList = new ArrayList<String>();
  • 8. Comparing List, List<?>, List<Object> List unboundedList = new ArrayList<Integer>(); // legal (warning) List<?> unboundedList = new ArrayList<Integer>(); // legal, partial type-safe List<?> unboundedList = new ArrayList<?>(); // illegal List<Object> unboundedList = new ArrayList<Integer>(); // illegal, invariant « List<sub> is not a subtype of List<super> »
  • 9. What is the difference? static int countCommonElements(Set s1, Set s2) { int result = 0; for (Object o1 : s1) { if (s2.contains( o1 )) result++; } return result; } static int countCommonElements(Set<?> s1, Set<?> s2) { int result = 0; for (Object o1 : s1) { if (s2.contains( o1 )) result++; } return result; }
  • 10. Arrays « sub[] is a subtype of super[], so its covariant » Object[] anObjectArray = new Integer[10]; // legal, covariant anObjectArray[0] = new String("abc"); // no type safety, causes runtime exception // like arrays, raw collection types arent’n type-safe List list = new ArrayList(); list.add("one"); list.add(new Integer(1)); String s = (String) list.get(1); // ClassCastException
  • 11. Boxing-Unboxing public static int sum (List<Integer> ints) { int s = 0; for (int n : ints) { s += n; } return s; } public static Integer sumInteger(List<Integer> ints) { Integer s = 0; for (Integer n : ints) { s += n; } return s; }
  • 12. public class Stack { private Object[] stack; private int top = 0; private static final int INITIAL_CAPACITY = 8; public Stack() { stack = new Object[INITIAL_CAPACITY]; } public void push(Object obj) { ensureCapacity(); stack[top++] = obj; } public Object pop() { if (top == 0) // stack is empty throw new EmptyStackException(); Object temp = stack[--top]; stack[top]=null; return temp; } public boolean isEmpty(){ return top == 0; } public void ensureCapacity() { if (stack.length == top) stack = Arrays.copyOf(stack, 2 * top + 1); } } public class GenericStack<E> { private E[] stack; private int top = 0; private static final int INITIAL_CAPACITY = 8; @SuppressWarnings( "unchecked" ) public GenericStack() { stack = (E[]) new Object[INITIAL_CAPACITY]; } public void push(E obj) { ensureCapacity(); stack[top++] = obj; } public E pop() { if (top == 0) // stack is empty return null; E temp = stack[--top]; stack[top]=null; return temp; } public boolean isEmpty(){ return top == 0; } public void ensureCapacity() { if (stack.length == top) stack = Arrays.copyOf(stack, 2 * top + 1); } } Generify legacy codes
  • 13. Generic methods public static <E> Set<E> union (Set<E> s1, Set<E> s2) «Static utility methods are good candidates for generification » formal type parameter return type type parameter
  • 14. Get and Put Principal // PECS (producer extends, consumer super) principal public static <T> void copy( List<? super T> dst, List<? extends T> src ) { for ( int i = 0; i < src.size(); i++ ) { dst.set( i, src.get( i ) ); } } // usage List<Object> objs = Arrays.<Object>asList(2, 3.14, "four"); List<Integer> ints = Arrays.asList(5, 6); Collections.copy(objs, ints); // type inference assert objs.toString().equals("[5, 6, four]");
  • 15. Copy method (alternatives) public static <T> void copy( List<T> dst, List<T> src); public static <T> void copy( List<T> dst, List<? extends T> src); public static <T> void copy( List<? super T> dst, List<T> src); public static <T> void copy( List<? super T> dst, List<? extends T> src);
  • 16. Comparables public static <T extends Comparable<T>> T max ( List<T> list); « All comparables and comparators are consumers » public static <T extends Comparable<? super T>> T max( List<? extends T> list);
  • 17. Tips on wildcard types «Use wildcard types on input parameters for maximum flexibility» «Do not use a wildcard for an input parameter if you both get and put on that parameter» « Do not use wildcard types as return types »
  • 18. Restrictions on Wildcards Instance Creation List<?> list = new ArrayList<?>(); // illegal List<List<?>> lists = new ArrayList<List<?>>(); // legal lists.add(Arrays.asList(1,2,3)); lists.add(Arrays.asList("four","five")); Generic Method Calls List<?> list = Lists.<?>factory(); // illegal List<List<?>> list = Lists.<List<?>>factory(); // legal Supertypes class AnyList extends ArrayList<?> {...} // illegal
  • 19. Wildcard capturing public static <T> void reverse(List<T> list) { List<T> tmp = new ArrayList<T>(list); for (int i = 0; i < list.size(); i++) { list.set(i, tmp.get(list.size() - i - 1)); } } public static void reverse(List<?> list) { List<Object> tmp = new ArrayList<Object>(list); for (int i = 0; i < list.size(); i++) { list.set(i, tmp.get(list.size() - i - 1)); // error } }
  • 20. Wildcard capturing (continue) public static void reverse(List<?> list) { rev(list); } private static <T> void rev(List<T> list) { List<T> tmp = new ArrayList<T>(list); for (int i = 0; i < list.size(); i++) { list.set(i, tmp.get(list.size() - i - 1)); } } « Here we say that the type variable T has captured the wildcard. This is a generally useful technique when dealing with wildcards, and it is worth knowing. »
  • 21. Use Checked Collections to Enforce Security private class Order { } private class AuthenticatedOrder extends Order { } .. List<AuthenticatedOrder> checkedList = new ArrayList<AuthenticatedOrder>(); addChecked(Collections.checkedList( checkedList, AuthenticatedOrder.class)); .. public void addChecked(List<AuthenticatedOrder> checkedList) { List raw = checkedList; Order order = new Order(); raw.add(order); // unchecked call, ClassCastException at runtime }