1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

Slides:



Advertisements
Similar presentations
Generic programming in Java
Advertisements

CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
Java Generics. 2 The Dark Ages: Before Java 5 Java relied only on inclusion polymorphism  A polymorphism code = Using a common superclass Every class.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
1 Chapter 21 Generics. 2 Objectives F To know the benefits of generics (§21.1). F To use generic classes and interfaces (§21.2). F To declare generic.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Generic Subroutines and Exceptions CS351 – Programming Paradigms.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Generic Java 21/ What is generics? To be able to assign type variables to a class These variables are not bound to any specific type until the.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Java Generics.
Generics In Java 1.5 By Manjunath Beeraladinni. Generics ➲ New feature in JDK1.5. ➲ Generic allow to abstract over types. ➲ Generics make the code clearer.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Effective Java: Generics Last Updated: Spring 2009.
CSC 243 – Java Programming, Spring 2013 March 12, 2013 Week 7, Generics.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Generics1 Parametrized classes and methods. Generics2 What are generics Generics are classes or interfaces that can be instantiated with a variety of.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
CSE 143 Lecture 4 ArrayList Reading: 10.1 slides created by Marty Stepp
CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Generics (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Generics CompSci 230 S Software Construction.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
CMSC 330: Organization of Programming Languages Java Generics.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
Polymorphism (generics) CSE 331 University of Washington.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION GENERICS/PARAMETRIC POLYMORPHISM Autumn 2011 We We Abstraction.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
GENERICS AND THE JAVA COLLECTIONS FRAMEWORK Lecture 16 CS2110 – Fall 2015 Photo credit: Andrew Kennedy.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Subtype Polymorphism, cont. Parametric Polymorphism and Java Generics.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.
Generics. Writing typed checked generic code There are many instances where the type of the object is irrelevant : –The construction of data structures.
1 CSE 331 The Object class; Object equality and the equals method slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
1 Chapter 21 Generics. 2 Objectives F To use generic classes and interfaces (§21.2). F To declare generic classes and interfaces (§21.3). F To understand.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
James Wilcox / Winter 2016 CSE 331 Software Design and Implementation Lecture 14 Generics 2.
CSC 520 – Advanced Object Oriented Programming, Fall, 2010 Thursday, September 30 Week 5, Generics and Inheritance Techniques, Meyer Ch. 10 & 16.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.
Building Java Programs Generics, hashing reading: 18.1.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets
Introducing Java Generics and Collections
Chapter 20 Generic Classes and Methods
A tree set Our SearchTree class is essentially a set.
Parametric Polymorphism and Java Generics
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Lecture 26: Advanced List Implementation
A tree set Our SearchTree class is essentially a set.
CSE 331 Software Design and Implementation
Generic programming in Java
Binary Search Trees continued; Tree Sets
slides created by Marty Stepp
CSE 373: Data Structures and Algorithms
CMSC 202 Generics.
CSE 143 Lecture 25 Advanced collection classes
Chapter 19 Generics.
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

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 name = new ArrayList (); Since Java 1.5, when constructing a java.util.ArrayList, we specify the type of elements it will contain between.  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 names = new ArrayList (); 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 { or public class name {  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 { 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 { private T myField; // ok private T[] myArray; // 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 {... 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 { 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 implements List {... public class LinkedList implements List {...

10 Generic methods public static 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 void copy(List dst, List src) { for (T t : src) { dst.add(t); }

11 Bounded type parameters  An upper bound; accepts the given supertype or any of its subtypes.  Works for multiple superclass/interfaces with & :  A lower bound; accepts the given supertype or any of its supertypes. Example: // tree set works for any comparable type public class TreeSet > {... }

12 Complex bounded types public static > T max(Collection c)  Find max value in any collection, if the elements can be compared. public static void copy( List dst, List 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 > void sort(List list)  Sort any list whose elements can be compared to the same type or a broader type.

13 Generics and subtyping Is List a subtype of List ? Is Set a subtype of Collection ? No. That would violate the Liskov Substitutability Principle.  If we could pass a Set to a method expecting a Collection, that method could add other animals. Set set1 = new HashSet (); Set 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 :  ? can become any particular type; Object is just one such type.  List is restrictive; wouldn't take a List Difference btwn. List and List :  The latter binds to a particular Foo subtype and allows ONLY that. e.g. List might store only Giraffes but not Zebras  The former allows anything that is a subtype of Foo in the same list. e.g. List 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 lst1 = new ArrayList (); List lst2 = new ArrayList (); lst1.getClass() == lst2.getClass() // true You cannot use instanceof to discover a type parameter. Collection cs = new ArrayList (); if (cs instanceof Collection ) { // illegal }

16 Generics and casting Casting to generic type results in a warning. List l = new ArrayList (); // ok List ls = (List ) 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 badCast(T t, Object o) { return (T) o; // unchecked warning }