SlideShare a Scribd company logo
1 of 16
1
SENG 201
Generics (Parametric Polymorphism)
2
Parametric polymorphism
• parametric polymorphism: Ability for a function or type to be written in such a
way that it handles values identically without depending on knowledge of their
types.
• Such a function or type is called a generic function or data type.
• first introduced in ML language in 1976
• now part of many other languages (Haskell, Java C#, Delphi)
• C++ templates are similar but lack various features/flexibility
• Motivation: Parametric polymorphism allows you to write flexible, general code
without sacrificing type safety.
• Most commonly used in Java with collections.
• Also used in reflection (seen later).
3
Java collections ≤ v1.4
• The initial Java collections stored values of type Object.
• They could store any type, since all types are subclasses of Object.
• But you had to cast the results, which was tedious and error-prone.
• Examining the elements of a collection was not type-safe.
// in Java 1.4:
ArrayList names = new ArrayList();
names.add("Marty Stepp");
names.add("Stuart Reges");
String teacher = (String) names.get(0);
// this will compile but crash at runtime; bad
Point oops = (Point) names.get(1);
4
Type Parameters (Generics)
List<Type> name = new ArrayList<Type>();
• Since Java 1.5, when constructing a java.util.ArrayList, we specify the
type of elements it will contain between < and >.
• We say that the ArrayList class accepts a type parameter,
or that it is a generic class.
• Use of the "raw type" ArrayList without <> leads to warnings.
List<String> names = new ArrayList<String>();
names.add("Marty Stepp");
names.add("Stuart Reges");
String teacher = names.get(0); // no cast
Point oops = (Point) names.get(1); // error
5
Implementing generics
// a parameterized (generic) class
public class name<Type> {
or
public class name<Type, Type, ..., Type> {
• By putting the Type in < >, you are demanding that any client that constructs your object
must supply a type parameter.
• You can require multiple type parameters separated by commas.
• The rest of your class's code can refer to that type by name.
• The convention is to use a 1-letter name such as:
T for Type, E for Element, N for Number, K for Key, or V for Value.
• The type parameter is instantiated by the client. (e.g. E → String)
6
Generics and arrays (15.4)
public class Foo<T> {
private T myField; // ok
private T[] myArray; // ok
public Foo(T param) {
myField = new T(); // error
myArray = new T[10]; // error
}
}
• You cannot create objects or arrays of a parameterized type.
7
Generics/arrays, fixed
public class Foo<T> {
private T myField; // ok
private T[] myArray; // ok
@SuppressWarnings("unchecked")
public Foo(T param) {
myField = param; // ok
T[] a2 = (T[]) (new Object[10]); // ok
}
}
• But you can create variables of that type, accept them as parameters, return them, or
create arrays by casting Object[].
• Casting to generic types is not type-safe, so it generates a warning.
8
Comparing generic objects
public class ArrayList<E> {
...
public int indexOf(E value) {
for (int i = 0; i < size; i++) {
// if (elementData[i] == value) {
if (elementData[i].equals(value)) {
return i;
}
}
return -1;
}
}
• When testing objects of type E for equality, must use equals
9
A generic interface
// Represents a list of values.
public interface List<E> {
public void add(E value);
public void add(int index, E value);
public E get(int index);
public int indexOf(E value);
public boolean isEmpty();
public void remove(int index);
public void set(int index, E value);
public int size();
}
public class ArrayList<E> implements List<E> { ...
public class LinkedList<E> implements List<E> { ...
10
Generic methods
public static <Type> returnType name(params) {
• When you want to make just a single (often static) method generic in a class,
precede its return type by type parameter(s).
public class Collections {
...
public static <T> void copy(List<T> dst, List<T> src) {
for (T t : src) {
dst.add(t);
}
}
}
11
Bounded type parameters
<Type extends SuperType>
• An upper bound; accepts the given supertype or any of its subtypes.
• Works for multiple superclass/interfaces with & :
<Type extends ClassA & InterfaceB & InterfaceC & ...>
<Type super SuperType>
• A lower bound; accepts the given supertype or any of its supertypes.
• Example:
// tree set works for any comparable type
public class TreeSet<T extends Comparable<T>> {
...
}
12
Complex bounded types
• public static <T extends Comparable<T>>
T max(Collection<T> c)
• Find max value in any collection, if the elements can be compared.
• public static <T> void copy(
List<T2 super T> dst, List<T3 extends T> src)
• Copy all elements from src to dst. For this to be reasonable, dst must be able to safely
store anything that could be in src. This means that all elements of src must be of dst's
element type or a subtype.
• public static <T extends Comparable<T2 super T>>
void sort(List<T> list)
• Sort any list whose elements can be compared to the same type or a broader type.
13
Generics and subtyping
• Is List<String> a subtype of List<Object>?
• Is Set<Giraffe> a subtype of Collection<Animal>?
• No. That would violate the Liskov Substitutability Principle.
• If we could pass a Set<Giraffe> to a method expecting a Collection<Animal>,
that method could add other animals.
Set<Giraffe> set1 = new HashSet<Giraffe>();
Set<Animal> set2 = set2; // illegal
...
set2.add(new Zebra());
Giraffe geoffrey = set1.get(0); // error
14
Wildcards
• ? indicates a wild-card type parameter, one that can be any type.
• List<?> list = new List<?>(); // anything
• Difference between List<?> and List<Object> :
• ? can become any particular type; Object is just one such type.
• List<Object> is restrictive; wouldn't take a List<String>
• Difference btwn. List<Foo> and List<? extends Foo>:
• The latter binds to a particular Foo subtype and allows ONLY that.
• e.g. List<? extends Animal> might store only Giraffes but not Zebras
• The former allows anything that is a subtype of Foo in the same list.
• e.g. List<Animal> could store both Giraffes and Zebras
15
Type erasure
• All generics types become type Object once compiled.
• One reason: Backward compatibility with old byte code.
• At runtime, all generic instantiations have the same type.
List<String> lst1 = new ArrayList<String>();
List<Integer> lst2 = new ArrayList<Integer>();
lst1.getClass() == lst2.getClass() // true
• You cannot use instanceof to discover a type parameter.
Collection<?> cs = new ArrayList<String>();
if (cs instanceof Collection<String>) {
// illegal
}
Generics and casting
• Casting to generic type results in a warning.
List<?> l = new ArrayList<String>(); // ok
List<String> ls = (List<String>) l; // warn
• The compiler gives an unchecked warning, since this isn't something the runtime system is
going to check for you.
• Usually, if you think you need to do this, you're doing it wrong.
• The same is true of type variables:
public static <T> T badCast(T t, Object o) {
return (T) o; // unchecked warning
}

More Related Content

Similar to Java Generics.ppt

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Javase5generics
Javase5genericsJavase5generics
Javase5genericsimypraz
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithmsNico Ludwig
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...GeeksLab Odessa
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scalaRuslan Shevchenko
 
What's new in c# 8.0
What's new in c# 8.0What's new in c# 8.0
What's new in c# 8.0Moaid Hathot
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithmsNico Ludwig
 
Tool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLTool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLNick Pruehs
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4thConnex
 

Similar to Java Generics.ppt (20)

core java
core javacore java
core java
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Javase5generics
Javase5genericsJavase5generics
Javase5generics
 
Generics_RIO.ppt
Generics_RIO.pptGenerics_RIO.ppt
Generics_RIO.ppt
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Java Generics - by Example
Java Generics - by ExampleJava Generics - by Example
Java Generics - by Example
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
Java/Scala Lab 2016. Руслан Шевченко: Несколько трюков scala-разработки, приг...
 
Few simple-type-tricks in scala
Few simple-type-tricks in scalaFew simple-type-tricks in scala
Few simple-type-tricks in scala
 
What's new in c# 8.0
What's new in c# 8.0What's new in c# 8.0
What's new in c# 8.0
 
(4) collections algorithms
(4) collections algorithms(4) collections algorithms
(4) collections algorithms
 
Tool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLTool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAML
 
Scala: A brief tutorial
Scala: A brief tutorialScala: A brief tutorial
Scala: A brief tutorial
 
Md03 - part3
Md03 - part3Md03 - part3
Md03 - part3
 
Presentation 4th
Presentation 4thPresentation 4th
Presentation 4th
 
Generics
GenericsGenerics
Generics
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 

Recently uploaded

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 

Recently uploaded (20)

Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 

Java Generics.ppt

  • 2. 2 Parametric polymorphism • parametric polymorphism: Ability for a function or type to be written in such a way that it handles values identically without depending on knowledge of their types. • Such a function or type is called a generic function or data type. • first introduced in ML language in 1976 • now part of many other languages (Haskell, Java C#, Delphi) • C++ templates are similar but lack various features/flexibility • Motivation: Parametric polymorphism allows you to write flexible, general code without sacrificing type safety. • Most commonly used in Java with collections. • Also used in reflection (seen later).
  • 3. 3 Java collections ≤ v1.4 • The initial Java collections stored values of type Object. • They could store any type, since all types are subclasses of Object. • But you had to cast the results, which was tedious and error-prone. • Examining the elements of a collection was not type-safe. // in Java 1.4: ArrayList names = new ArrayList(); names.add("Marty Stepp"); names.add("Stuart Reges"); String teacher = (String) names.get(0); // this will compile but crash at runtime; bad Point oops = (Point) names.get(1);
  • 4. 4 Type Parameters (Generics) List<Type> name = new ArrayList<Type>(); • Since Java 1.5, when constructing a java.util.ArrayList, we specify the type of elements it will contain between < and >. • We say that the ArrayList class accepts a type parameter, or that it is a generic class. • Use of the "raw type" ArrayList without <> leads to warnings. List<String> names = new ArrayList<String>(); names.add("Marty Stepp"); names.add("Stuart Reges"); String teacher = names.get(0); // no cast Point oops = (Point) names.get(1); // error
  • 5. 5 Implementing generics // a parameterized (generic) class public class name<Type> { or public class name<Type, Type, ..., Type> { • By putting the Type in < >, you are demanding that any client that constructs your object must supply a type parameter. • You can require multiple type parameters separated by commas. • The rest of your class's code can refer to that type by name. • The convention is to use a 1-letter name such as: T for Type, E for Element, N for Number, K for Key, or V for Value. • The type parameter is instantiated by the client. (e.g. E → String)
  • 6. 6 Generics and arrays (15.4) public class Foo<T> { private T myField; // ok private T[] myArray; // ok public Foo(T param) { myField = new T(); // error myArray = new T[10]; // error } } • You cannot create objects or arrays of a parameterized type.
  • 7. 7 Generics/arrays, fixed public class Foo<T> { private T myField; // ok private T[] myArray; // ok @SuppressWarnings("unchecked") public Foo(T param) { myField = param; // ok T[] a2 = (T[]) (new Object[10]); // ok } } • But you can create variables of that type, accept them as parameters, return them, or create arrays by casting Object[]. • Casting to generic types is not type-safe, so it generates a warning.
  • 8. 8 Comparing generic objects public class ArrayList<E> { ... public int indexOf(E value) { for (int i = 0; i < size; i++) { // if (elementData[i] == value) { if (elementData[i].equals(value)) { return i; } } return -1; } } • When testing objects of type E for equality, must use equals
  • 9. 9 A generic interface // Represents a list of values. public interface List<E> { public void add(E value); public void add(int index, E value); public E get(int index); public int indexOf(E value); public boolean isEmpty(); public void remove(int index); public void set(int index, E value); public int size(); } public class ArrayList<E> implements List<E> { ... public class LinkedList<E> implements List<E> { ...
  • 10. 10 Generic methods public static <Type> returnType name(params) { • When you want to make just a single (often static) method generic in a class, precede its return type by type parameter(s). public class Collections { ... public static <T> void copy(List<T> dst, List<T> src) { for (T t : src) { dst.add(t); } } }
  • 11. 11 Bounded type parameters <Type extends SuperType> • An upper bound; accepts the given supertype or any of its subtypes. • Works for multiple superclass/interfaces with & : <Type extends ClassA & InterfaceB & InterfaceC & ...> <Type super SuperType> • A lower bound; accepts the given supertype or any of its supertypes. • Example: // tree set works for any comparable type public class TreeSet<T extends Comparable<T>> { ... }
  • 12. 12 Complex bounded types • public static <T extends Comparable<T>> T max(Collection<T> c) • Find max value in any collection, if the elements can be compared. • public static <T> void copy( List<T2 super T> dst, List<T3 extends T> src) • Copy all elements from src to dst. For this to be reasonable, dst must be able to safely store anything that could be in src. This means that all elements of src must be of dst's element type or a subtype. • public static <T extends Comparable<T2 super T>> void sort(List<T> list) • Sort any list whose elements can be compared to the same type or a broader type.
  • 13. 13 Generics and subtyping • Is List<String> a subtype of List<Object>? • Is Set<Giraffe> a subtype of Collection<Animal>? • No. That would violate the Liskov Substitutability Principle. • If we could pass a Set<Giraffe> to a method expecting a Collection<Animal>, that method could add other animals. Set<Giraffe> set1 = new HashSet<Giraffe>(); Set<Animal> set2 = set2; // illegal ... set2.add(new Zebra()); Giraffe geoffrey = set1.get(0); // error
  • 14. 14 Wildcards • ? indicates a wild-card type parameter, one that can be any type. • List<?> list = new List<?>(); // anything • Difference between List<?> and List<Object> : • ? can become any particular type; Object is just one such type. • List<Object> is restrictive; wouldn't take a List<String> • Difference btwn. List<Foo> and List<? extends Foo>: • The latter binds to a particular Foo subtype and allows ONLY that. • e.g. List<? extends Animal> might store only Giraffes but not Zebras • The former allows anything that is a subtype of Foo in the same list. • e.g. List<Animal> could store both Giraffes and Zebras
  • 15. 15 Type erasure • All generics types become type Object once compiled. • One reason: Backward compatibility with old byte code. • At runtime, all generic instantiations have the same type. List<String> lst1 = new ArrayList<String>(); List<Integer> lst2 = new ArrayList<Integer>(); lst1.getClass() == lst2.getClass() // true • You cannot use instanceof to discover a type parameter. Collection<?> cs = new ArrayList<String>(); if (cs instanceof Collection<String>) { // illegal }
  • 16. Generics and casting • Casting to generic type results in a warning. List<?> l = new ArrayList<String>(); // ok List<String> ls = (List<String>) l; // warn • The compiler gives an unchecked warning, since this isn't something the runtime system is going to check for you. • Usually, if you think you need to do this, you're doing it wrong. • The same is true of type variables: public static <T> T badCast(T t, Object o) { return (T) o; // unchecked warning }