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

PPTX
Java Methods
PPTX
Java script
PPT
Java Arrays
PPTX
Hash table in java
PDF
Asp.net mvc basic introduction
PDF
Generics and collections in Java
PDF
Demystify LDAP and OIDC Providing Security to Your App on Kubernetes
PPTX
VB.NET:An introduction to Namespaces in .NET framework
Java Methods
Java script
Java Arrays
Hash table in java
Asp.net mvc basic introduction
Generics and collections in Java
Demystify LDAP and OIDC Providing Security to Your App on Kubernetes
VB.NET:An introduction to Namespaces in .NET framework

What's hot (20)

PPT
ASP.NET MVC Presentation
PDF
HTML codes 1
PPTX
ASP.NET Page Life Cycle
PPT
PHP - Introduction to PHP AJAX
PPTX
Asp.net and .Net Framework ppt presentation
PPTX
PPTX
Collections and its types in C# (with examples)
DOCX
Lab manual asp.net
PDF
Java Collections Tutorials
PPT
Asp.net server controls
PPT
JavaScript Basics
PDF
What are Abstract Classes in Java | Edureka
PDF
React Context API
PPSX
Collections - Lists, Sets
PPT
Taking User Input in Java
PDF
01 clases y objetos, POO Visual Basic .NET
PPTX
20.3 Java encapsulation
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPT
JQuery introduction
ASP.NET MVC Presentation
HTML codes 1
ASP.NET Page Life Cycle
PHP - Introduction to PHP AJAX
Asp.net and .Net Framework ppt presentation
Collections and its types in C# (with examples)
Lab manual asp.net
Java Collections Tutorials
Asp.net server controls
JavaScript Basics
What are Abstract Classes in Java | Edureka
React Context API
Collections - Lists, Sets
Taking User Input in Java
01 clases y objetos, POO Visual Basic .NET
20.3 Java encapsulation
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
JQuery introduction
Ad

Viewers also liked (10)

PDF
Interfaces en java
PPTX
Clases abstractas e interfaces en java
PPTX
Interfaces en Java
PPTX
Java interfaces
PDF
POO - 17 - Interfaces
PPT
Poo Java
PDF
¿Qué es una interface en java?
PPTX
Interfaces en Java
PPTX
Clases abstractas e interfaces
PDF
Generics
Interfaces en java
Clases abstractas e interfaces en java
Interfaces en Java
Java interfaces
POO - 17 - Interfaces
Poo Java
¿Qué es una interface en java?
Interfaces en Java
Clases abstractas e interfaces
Generics
Ad

Similar to Java Generics (20)

PPT
Java Generics for Dummies
PPT
Effective Java - Generics
PDF
Java Generics - by Example
PDF
Java Generics - by Example
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PPT
Java Generics.ppt
PDF
Javase5generics
PPTX
Generics of JAVA
PPT
Java Generics
PPT
Generics Module 2Generics ModuleGenerics Module 2
PDF
Generics Past, Present and Future (Latest)
ODP
javasebeyondbasics
PDF
Java Generics Introduction - Syntax Advantages and Pitfalls
PPTX
Collection in java to store multiple values.pptx
PDF
Generics past, present and future
PPT
Applying Generics
PPT
Generic Programming seminar
PDF
Java Generics wildcards
PDF
Introducing generic types
PPTX
Collections in object oriented programming
Java Generics for Dummies
Effective Java - Generics
Java Generics - by Example
Java Generics - by Example
Generic Types in Java (for ArtClub @ArtBrains Software)
Java Generics.ppt
Javase5generics
Generics of JAVA
Java Generics
Generics Module 2Generics ModuleGenerics Module 2
Generics Past, Present and Future (Latest)
javasebeyondbasics
Java Generics Introduction - Syntax Advantages and Pitfalls
Collection in java to store multiple values.pptx
Generics past, present and future
Applying Generics
Generic Programming seminar
Java Generics wildcards
Introducing generic types
Collections in object oriented programming

Recently uploaded (20)

PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
System and Network Administration Chapter 2
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
AI in Product Development-omnex systems
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Nekopoi APK 2025 free lastest update
PDF
medical staffing services at VALiNTRY
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
history of c programming in notes for students .pptx
PPTX
L1 - Introduction to python Backend.pptx
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Navsoft: AI-Powered Business Solutions & Custom Software Development
PPTX
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PDF
PTS Company Brochure 2025 (1).pdf.......
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
top salesforce developer skills in 2025.pdf
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
System and Network Administration Chapter 2
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
AI in Product Development-omnex systems
ManageIQ - Sprint 268 Review - Slide Deck
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Nekopoi APK 2025 free lastest update
medical staffing services at VALiNTRY
How to Migrate SBCGlobal Email to Yahoo Easily
history of c programming in notes for students .pptx
L1 - Introduction to python Backend.pptx
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Navsoft: AI-Powered Business Solutions & Custom Software Development
CHAPTER 12 - CYBER SECURITY AND FUTURE SKILLS (1) (1).pptx
PTS Company Brochure 2025 (1).pdf.......
Operating system designcfffgfgggggggvggggggggg
top salesforce developer skills in 2025.pdf

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 }