CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Similar documents
Announcements. Lecture 14 Generics 1. Announcements. CSE 331 Software Design and Implementation. Leah Perlmutter / Summer 2018

CSE 331 Software Design and Implementation. Lecture 14 Generics 1

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation

Polymorphism (generics)

Parametric polymorphism and Generics

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Announcements. Lecture 15 Generics 2. Announcements. Big picture. CSE 331 Software Design and Implementation

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

301AA - Advanced Programming [AP-2017]

301AA - Advanced Programming [AP-2017]

CSE 331. Generics (Parametric Polymorphism)

CSE Lecture 7: Polymorphism and generics 16 September Nate Nystrom UTA

COMP6700/2140 Generic Methods

Software Engineering. Prof. Agostino Poggi

Exam 2. Topics. Preconditions vs. Exceptions. Exam 2 Review. Exam 2 on Thursday, March 29 th. Closed book, closed computer, closed phone

Exercise 8 Parametric polymorphism November 17, 2017

Advanced Programming Generics Collections

Exercise 8 Parametric polymorphism November 18, 2016

CS61B Lecture #23. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

CSE 331 Summer 2017 Final Exam. The exam is closed book and closed electronics. One page of notes is allowed.

Chapter 4 Defining Classes I

Specifications. CSE 331 Spring 2010

Java Generics -- an introduction. Based on

Lecture 4 Specifications

Generic Universe Types in JML

The list abstract data type defined a number of operations that all list-like objects ought to implement:

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 19 19:36: CS61B: Lecture #25 1

generic programming alberto ferrari university of parma

Design Patterns (1) CSE 331 Spring 2010

CSCE 314 Programming Languages

CS61B Lecture #25: Java Generics. Last modified: Thu Oct 18 21:04: CS61B: Lecture #25 1

CS61B Lecture #24. Today: Java support for generic programming. Readings for today: A Java Reference, Chapter 10.

Why Use Generics? Generic types Generic methods Bounded type parameters Generics, Inheritance, and Subtypes Wildcard types

Announcements. Specifications. Outline. Specifications. HW1 is due Thursday at 1:59:59 pm

CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping. Dan Grossman Winter 2013

Javarifier: inference of reference immutability

The collections interfaces

Generic programming in OO Languages

301AA - Advanced Programming [AP-2017]

Comp215: Thinking Generically

Generics. Computer Science and Engineering College of Engineering The Ohio State University. Lecture 10

Representation Invariants and Abstraction Functions

Refactoring Java Generics by Inferring Wildcards, In Practice

11/7/18 JAVA GENERICS. Java Collections. Java Collections. Using Java Collections. Proposals for adding Generics to Java.

CSC 172 Data Structures and Algorithms. Lecture 3 Spring 2018 TuTh 3:25 pm 4:40 pm

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Self Type Constructors. Atsushi Igarashi Kyoto University Joint work with Chieri Saito

Photo credit: Andrew Kennedy JAVA GENERICS

Introducing Generics

C# Generics. Object Oriented Programming (236703) Winter

Generics, I/O & Regular Expressions Maria Zontak

Object Oriented Issues in VDM++

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Rules and syntax for inheritance. The boring stuff

Generics עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Java Brand Generics. Advanced Topics in Java. Khalid Azim Mughal Version date:

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Quiz. Programming Languages. CSE 130 : Fall Lecture 16: Static Types for Objects. Ranjit Jhala UC San Diego

Collections, Maps and Generics

CS152: Programming Languages. Lecture 24 Bounded Polymorphism; Classless OOP. Dan Grossman Spring 2011

1. Every program must have at least one class declaration. (*) 2. Every class declared in a program must have a distinct identifier.

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

CS Introduction to Data Structures Week 1 Thursday

Generic Collections. Chapter The Object class

CSE 331 Software Design & Implementation

Tradeoffs. CSE 505: Programming Languages. Lecture 15 Subtyping. Where shall we add useful completeness? Where shall we add completeness?

Array Basics: Outline. Creating and Accessing Arrays. Creating and Accessing Arrays. Arrays (Savitch, Chapter 7)

More than you ever wanted to know about. Java Generics. Jeff Meister CMSC 420 Summer 2007

Generalizing Collection Classes Using Generics with other Java 1.5 Features Integration of Generics with Previous Releases User built generic classes

CSE 331 Software Design and Implementation. Lecture 4 Specifications

Subtyping for behaviour?

6. Generic and Virtual Types

JAVA V Assertions Java, winter semester

CS-XXX: Graduate Programming Languages. Lecture 23 Types for OOP; Static Overloading and Multimethods. Dan Grossman 2012

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. The Collection Framework

Subtypes and Subclasses

CS 251 Intermediate Programming Inheritance

CS-202 Introduction to Object Oriented Programming

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

Typing issues JAVA GENERICS. ! Parametric Polimorphism. ! Bounded Polymorphism. ! F- Bounded Polymorphism 10/28/13. Examples and Problems

Generics with Type Bounds

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

Lecture 7: Data Abstractions

CSE332: Data Abstrac0ons Sec%on 1. Hye In Kim Winter 2014

Building Java Programs

CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

JAVA V Source files Java, winter semester

Exam Review. CSE 331 Section 10 12/6/12. Slides by Kellen Donohue with material from Mike Ernst

Polymorphic (Generic) Programming in Java

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

EPITA Première Année Cycle Ingénieur. Atelier Java - J2

COMP6700/2140 Generic Types

CMSC 330: Organization of Programming Languages

Generic classes & the Java Collections Framework. *Really* Reusable Code

Transcription:

CSE 331 Software Design and Implementation Lecture 13 Generics 1 Zach Tatlock / Spring 2018

Varieties of abstraction Abstraction over computation: procedures (methods) int x1, y1, x2, y2; Math.sqrt(x1*x1 + y1*y1); Math.sqrt(x2*x2 + y2*y2); Abstraction over data: ADTs (classes, interfaces) Point p1, p2; Abstraction over types: polymorphism (generics) Point<Integer>, Point<Double> Today!

Why we abstraction Hide details Avoid distraction Permit details to change later Give a meaningful name to a concept Permit reuse in new contexts Avoid duplication: error-prone, confusing Save reimplementation effort Helps to Don t Repeat Yourself

Related abstractions interface ListOfStrings { boolean add(string elt); String get(int index); interface ListOfNumbers { boolean add(number elt); Number get(int index);

Related abstractions interface ListOfStrings { boolean add(string elt); String get(int index); interface ListOfNumbers { boolean add(number elt); Number get(int index); and many, many more // Type abstraction // abstracts over element type E interface List<E> { boolean add(e n); E get(int index); Type abstraction lets us use these types: List<String> List<Number> List<Integer> List<List<String>>

Formal parameter vs. type parameter interface ListOfIntegers { boolean add(integer elt); Integer get(int index); Declares a new variable, called a (formal) parameter Instantiate with any expression of the right type E.g., lst.add(7) Type of add is Integer boolean interface List<E> { boolean add(e n); E get(int index); Declares a new type variable, called a type parameter Instantiate with any (reference) type E.g., List<String> Type of List is Type Type Never just use List (in Java for backward compatiblity)

Type variables are types Declaration class NewSet<T> implements Set<T> { // rep invariant: // non-null, contains no duplicates // List<T> therep; T lastiteminserted; UseUse

Declaring and instantiating generics class MyClass<TypeVar1,, TypeVarN> { interface MyInterface<TypeVar1,, TypeVarN> { Convention: Type variable has one-letter name such as: T for Type, E for Element, K for Key, V for Value, To instantiate a generic class/interface, client supplies type arguments: MyClass<String,, Date>

Restricting instantiations by clients boolean add1(object elt); boolean add2(number elt); add1(new Date()); // OK add2(new Date()); // compile-time error Upper bounds interface List1<E extends Object> { interface List2<E extends Number> { List1<Date> // OK, Date is a subtype of Object List2<Date> // compile-time error, Date is not a // subtype of Number

Declaring and instantiating generics: syntax with bounds class MyClass<TypeVar1 extends TypeBound1,..., TypeVarN extends TypeBoundN> { (same for interface definitions) (default upper bound is Object) To instantiate a generic class/interface, client supplies type arguments: MyClass<String,, Date> Compile-time error if type is not a subtype of the upper bound

Using type variables Code can perform any operation permitted by the bound Because we know all instantiations will be subtypes! An enforced precondition on type instantiations class Foo1<E extends Object> { void m(e arg) { arg.asint(); // compiler error, E might not // support asint() class Foo2<E extends Number> { void m(e arg) { arg.asint(); // OK, since Number and its // subtypes support asint()

More examples public class Graph<N> implements Iterable<N> { private final Map<N, Set<N>> node2neighbors; public Graph(Set<N> nodes, Set<Tuple<N,N>> edges){ public interface Path<N, P extends Path<N,P>> extends Iterable<N>, Comparable<Path<?,?>> { public Iterator<N> iterator(); Do NOT copy/paste this stuff into your project unless it is what you want And you understand it!

More bounds <TypeVar extends SuperType> An upper bound; accepts given supertype or any of its subtypes <TypeVar extends ClassA & InterfaceB & InterfaceC & > Multiple upper bounds (superclass/interfaces) with & Recursively-defined bounds: // TreeSet works for any type that can be compared // to itself. public class TreeSet<T extends Comparable<T>> {

Outline Basics of generic types for classes and interfaces Basics of bounding generics Generic methods [not just using type parameters of class] Generics and subtyping Using bounds for more flexible subtyping Using wildcards for more convenient bounds Related digression: Java s array subtyping Java realities: type erasure Unchecked casts equals interactions Creating generic arrays

Generic classes are not enough class Utils { static double sumlist(list<number> lst) { double result = 0.0; for (Number n : lst) { result += n.doublevalue(); return result; static Object choose(list<object> lst) { int i = // random number < lst.size return lst.get(i); Reminder: static means no receiver (this parameter). Independent of Number above Cannot pass List<Double> List<Double> is not a subtype of List<Number>! We will see why soon.

Weaknesses of generic classes Would like to use sumlist for any subtype of Number For example, Double or Integer But as we will see, List<Double> is not a subtype of List<Number> Would like to use choose for any element type i.e., any subclass of Object No need to restrict to subclasses of Number Want to tell clients more about return type than Object Class Utils is not generic, but the methods should be generic

Generic methods solve the problem Have to declare class Utils { type parameter(s) static <T1 extends Number> double sumlist(list<t1> lst) { double result = 0.0; for (Number n : lst) { // T1 also works result += n.doublevalue(); return result; Have to declare static <T2> type parameter(s) T2 choose(list<t2> lst) { int i = // random number < lst.size return lst.get(i);

Using generics in methods Instance methods can use type parameters of the class Instance methods and static methods can have their own type parameters Generic methods Callers to generic methods need not explicitly instantiate the methods type parameters Compiler usually figures it out for you Type inference

More examples <T extends Comparable<T>> T max(collection<t> c) { <T extends Comparable<T>> void sort(list<t> list) { // use list.get() and T s compareto (This one works, but we will make it even more useful later by adding more bounds.) <T> void copyto(list<t> dst, List<T> src) { for (T t : src) dst.add(t);

Outline Basics of generic types for classes and interfaces Basics of bounding generics Generic methods [not just using type parameters of class] Generics and subtyping Using bounds for more flexible subtyping Using wildcards for more convenient bounds Related digression: Java s array subtyping Java realities: type erasure Unchecked casts equals interactions Creating generic arrays

Generics and subtyping Number Integer List<Number>? List<Integer> Integer is a subtype of Number Is List<Integer> a subtype of List<Number>? Use subtyping rules (stronger, weaker) to find out

List<Number> and List<Integer> interface List<T> { boolean add(t elt); T get(int index); So type List<Number> has: boolean add(number elt); Number get(int index); Number Integer List<Number> List<Integer> So type List<Integer> has: boolean add(integer elt); Integer get(int index); List<Integer> List<Number> Java subtyping is invariant with respect to generics Neither List<Number> nor List<Integer> subtype of other Not covariant and not contravariant

How to remember the invariant rule If Type2 and Type3 are different, then Type1<Type2> is not a subtype of Type1<Type3> Previous example shows why: Observer method prevents one direction Mutator/producer method prevents the other direction If our types have only observers or only mutators, then one direction of subtyping would be sound Java s type system is not expressive enough to allow this

Read-only allows covariance interface ReadOnlyList<T> { T get(int index); Number Integer ROList<Number> ROList<Integer> Type ReadOnlyList<Number> has method: Number get(int index); Type ReadOnlyList<Integer> has method: Integer get(int index); So covariant subtyping would be correct: ROList<Integer> is a subtype of ROList<Number> Covariant = type of ROList<T> changes the same way T changes The Java type system conservatively disallows this subtyping

Write-only allows contravariance interface WriteOnlyList<T> { boolean add(t elt); Number Integer WOList<Integer> WOList<Number> Type WriteOnlyList<Number> has method: boolean add(number elt); Type WriteOnlyList<Integer> has method: boolean add(integer elt); So contravariant subtyping would be correct: WOList<Number> is a subtype of WOList<Integer> Contravariant = type of ROList<T> changes opposite to T The Java type system conservatively disallows this subtyping

Generic types and subtyping List<Integer> and List<Number> are not subtype-related Generic types can have subtyping relationships Example: If HeftyBag extends Bag, then HeftyBag<Integer> is a subtype of Bag<Integer> HeftyBag<Number> is a subtype of Bag<Number> HeftyBag<String> is a subtype of Bag<String>

Outline Basics of generic types for classes and interfaces Basics of bounding generics Generic methods [not just using type parameters of class] Generics and subtyping Using bounds for more flexible subtyping Using wildcards for more convenient bounds Related digression: Java s array subtyping Java realities: type erasure Unchecked casts equals interactions Creating generic arrays