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

More Related Content

What's hot (20)

PPT
Major Java 8 features
Sanjoy Kumar Roy
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPTX
Java Final Keyword
Ducat India
 
PPT
PL/SQL Introduction and Concepts
Bharat Kalia
 
PPTX
JAVA AWT
shanmuga rajan
 
PDF
5 collection framework
Minal Maniar
 
PPTX
Presentation on-exception-handling
Nahian Ahmed
 
PPT
Exception handling
Tata Consultancy Services
 
PPT
Java tutorial PPT
Intelligo Technologies
 
PPTX
Core java
Ravi varma
 
PPT
sets and maps
Rajkattamuri
 
PPTX
Constructor in java
Hitesh Kumar
 
PDF
Java 8 features
NexThoughts Technologies
 
PDF
Java Generics - by Example
CodeOps Technologies LLP
 
PDF
07 java collection
Abhishek Khune
 
PPTX
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
PPTX
Chapter 3 servlet & jsp
Jafar Nesargi
 
PDF
Java8 features
Elias Hasnat
 
PPTX
L14 exception handling
teach4uin
 
Major Java 8 features
Sanjoy Kumar Roy
 
Core java complete ppt(note)
arvind pandey
 
Java Final Keyword
Ducat India
 
PL/SQL Introduction and Concepts
Bharat Kalia
 
JAVA AWT
shanmuga rajan
 
5 collection framework
Minal Maniar
 
Presentation on-exception-handling
Nahian Ahmed
 
Exception handling
Tata Consultancy Services
 
Java tutorial PPT
Intelligo Technologies
 
Core java
Ravi varma
 
sets and maps
Rajkattamuri
 
Constructor in java
Hitesh Kumar
 
Java 8 features
NexThoughts Technologies
 
Java Generics - by Example
CodeOps Technologies LLP
 
07 java collection
Abhishek Khune
 
Collections and its types in C# (with examples)
Aijaz Ali Abro
 
Chapter 3 servlet & jsp
Jafar Nesargi
 
Java8 features
Elias Hasnat
 
L14 exception handling
teach4uin
 

Viewers also liked (10)

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

Similar to Java Generics (20)

PPT
Java Generics for Dummies
knutmork
 
PPT
Effective Java - Generics
Roshan Deniyage
 
PDF
Java Generics - by Example
Ganesh Samarthyam
 
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
PPT
Java Generics.ppt
brayazar
 
PDF
Javase5generics
imypraz
 
PPTX
Generics of JAVA
Jai Marathe
 
PPT
Java Generics
jeslie
 
PPT
Generics Module 2Generics ModuleGenerics Module 2
AlvasCSE
 
PDF
Generics Past, Present and Future (Latest)
RichardWarburton
 
ODP
javasebeyondbasics
webuploader
 
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
PPTX
Collection in java to store multiple values.pptx
ASHUTOSH TRIVEDI
 
PDF
Generics past, present and future
RichardWarburton
 
PPT
Applying Generics
Bharat17485
 
PPT
Generic Programming seminar
Gautam Roy
 
PDF
Java Generics wildcards
Kohei Nozaki
 
PDF
Introducing generic types
Ivelin Yanev
 
PPTX
Collections in object oriented programming
KaranAgrawal78
 
PPTX
Java generics final
Akshay Chaudhari
 
Java Generics for Dummies
knutmork
 
Effective Java - Generics
Roshan Deniyage
 
Java Generics - by Example
Ganesh Samarthyam
 
Generic Types in Java (for ArtClub @ArtBrains Software)
Andrew Petryk
 
Java Generics.ppt
brayazar
 
Javase5generics
imypraz
 
Generics of JAVA
Jai Marathe
 
Java Generics
jeslie
 
Generics Module 2Generics ModuleGenerics Module 2
AlvasCSE
 
Generics Past, Present and Future (Latest)
RichardWarburton
 
javasebeyondbasics
webuploader
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Rakesh Waghela
 
Collection in java to store multiple values.pptx
ASHUTOSH TRIVEDI
 
Generics past, present and future
RichardWarburton
 
Applying Generics
Bharat17485
 
Generic Programming seminar
Gautam Roy
 
Java Generics wildcards
Kohei Nozaki
 
Introducing generic types
Ivelin Yanev
 
Collections in object oriented programming
KaranAgrawal78
 
Java generics final
Akshay Chaudhari
 
Ad

Recently uploaded (20)

PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
PPTX
Tally software_Introduction_Presentation
AditiBansal54083
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
PPTX
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
Finding Your License Details in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Wondershare PDFelement Pro Crack for MacOS New Version Latest 2025
bashirkhan333g
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
vMix Pro 28.0.0.42 Download vMix Registration key Bundle
kulindacore
 
Tally software_Introduction_Presentation
AditiBansal54083
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Tally_Basic_Operations_Presentation.pptx
AditiBansal54083
 
Customise Your Correlation Table in IBM SPSS Statistics.pptx
Version 1 Analytics
 
TheFutureIsDynamic-BoxLang witch Luis Majano.pdf
Ortus Solutions, Corp
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
4K Video Downloader Plus Pro Crack for MacOS New Download 2025
bashirkhan333g
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 

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 }