Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1.

Slides:



Advertisements
Similar presentations
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Advertisements

DATA STRUCTURES Lecture: Interfaces Slides adapted from Prof. Steven Roehrig.
Java Review Interface, Casting, Generics, Iterator.
Generic programming in Java
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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 L39 Generics (1). 2 OBJECTIVES  To create generic methods that perform identical tasks on arguments of different types.  To create a generic Stack.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
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.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
ADSA: Subtypes/ Advanced Data Structures and Algorithms Objective –explain how subtyping/subclassing and generics are combined in Java –introduce.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
1-1 Generic Types in Java Format for a generic (parameterized) type and instantiation of a generic type.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
Effective Java: Generics Last Updated: Spring 2009.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Generic abstraction  Genericity  Generic classes  Generic procedures Programming Languages 3 © 2012 David A Watt, University of Glasgow.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Copyright © 2002, Systems and Computer Engineering, Carleton University a-JavaReview.ppt * Object-Oriented Software Development Unit.
Self Type Constructors Atsushi Igarashi Kyoto University Joint work with Chieri Saito 1.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
CSE 331 Software Design & Implementation Dan Grossman Winter 2014 Generics (Based on slides by Mike Ernst, David Notkin, Hal Perkins)
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.
Types in programming languages1 What are types, and why do we need them?
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
CMSC 330: Organization of Programming Languages Java Generics.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSCE 314 Programming Languages Java Generics II Dr. Hyunyoung Lee 1.
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.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Subtype Polymorphism, cont. Parametric Polymorphism and Java Generics.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Object Oriented Programming in Java Habib Rostami Lecture 7.
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.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
(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.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
OOP Tirgul 10. What We’ll Be Seeing Today  Generics – A Reminder  Type Safety  Bounded Type Parameters  Generic Methods  Generics and Inner Classes.
Parametric Polymorphism and Java Generics. Today’s Lecture Outline Subtype polymorphism Subtyping vs. subclassing Liskov Substitution Principle (LSP)
A tree set Our SearchTree class is essentially a set.
Parametric Polymorphism and Java Generics
CSE 331 Software Design & Implementation
CSE 331 Software Design and Implementation
CSE 331 Software Design and Implementation
Generics (Parametric Polymorphism)
CSE 331 Software Design and Implementation
A tree set Our SearchTree class is essentially a set.
CSE 331 Software Design and Implementation
CSE 331 Software Design & Implementation
Generic programming in Java
CSE341: Programming Languages Lecture 25 Subtyping for OOP; Comparing/Combining Generics and Subtyping Zach Tatlock Winter 2018.
CSE331 SU Final Simple Summary
CSE 331 Software Design and Implementation
Presentation transcript:

Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 13 Generics 1

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, Point Today!

Why we <3 love <3 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”

Any true wizard knows, once you know the name of a thing you can control it. -- Jerry Sussman

Related abstractions interface ListOfNumbers { boolean add(Number elt); Number get(int index); } interface ListOfIntegers { boolean add(Integer elt); Integer get(int index); } … and many, many more // abstracts over element type interface List { boolean add(E n); E get(int index); } Lets us use types List List List > …

An analogous parameter interface ListOfIntegers { boolean add(Integer elt); Integer get(int index); } interface List { boolean add(E n); E 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 Declares a new type variable, called a type parameter Instantiate with any (reference) type E.g., List “Type” of List is Type  Type Never just use List (in Java for backward-compatiblity)

class NewSet implements Set { // rep invariant: // non-null, contains no duplicates // … List theRep; T lastItemInserted; … } Type variables are types Declaration Use

Declaring and instantiating generics class Name {…} interface Name {…} –Convention: 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: Name

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

Revised definition class Name<TypeVar1 extends Type1,..., TypeVarN extends TypeN> {…} –(same for interface definitions) –(default upper bound is Object ) To instantiate a generic class/interface, client supplies type arguments: Name 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 { void m(E arg) { arg.asInt(); // compiler error, E might not // support asInt } class Foo2 { void m(E arg) { arg.asInt(); // OK, since Number and its // subtypes support asInt }

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

More bounds –An upper bound; accepts given supertype or any of its subtypes –Multiple upper bounds (superclass/interfaces) with & Example: // tree set works for any comparable type public class TreeSet > { … }

Where are we? Done: –Basics of generic types for classes and interfaces –Basics of bounding generics Now: –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

Not all generics are for collections class Utils { static double sumList(List lst) { double result = 0.0; for (Number n : lst) { result += n.doubleValue(); } return result; } static Number choose(List lst) { int i = … // random number < lst.size return lst.get(i); }

Weaknesses Would like to use sumList for any subtype of Number –For example, Double or Integer –But as we will see, List is not a subtype of List 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

Much better class Utils { static double sumList(List lst) { double result = 0.0; for (Number n : lst) { // T also works result += n.doubleValue(); } return result; } static T choose(List lst) { int i = … // random number < lst.size return lst.get(i); } Have to declare type parameter(s)

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 just figures it out for you –Type inference

More examples > T max(Collection c) { … } > void sort(List list) { // … use list.get() and T’s compareTo } (This one “works” but will make it even more useful later by adding more bounds) void copyTo(List dst, List src) { for (T t : src) dst.add(t); }

Where are we? Done: –Basics of generic types for classes and interfaces –Basics of bounding generics Now: –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 Integer is a subtype of Number Is List a subtype of List ? Use subtyping rules (stronger, weaker) to find out… Number Integer List ?

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

Hard to remember? If Type2 and Type3 are different, then Type1 is not a subtype of Type1 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 –But Java’s type system does not “notice this” so such subtyping is never allowed in Java

Read-only allows covariance interface List { T get(int index); } So type List has: Number get(int index); So type List has: Integer get(int index); So covariant subtyping would be correct: –List a subtype of List But Java does not analyze interface definitions like this –Conservatively disallows this subtyping Number Integer

Write-only allows contravariance interface List { boolean add(T elt); } So type List has: boolean add(Number elt); So type List has: boolean add(Integer elt); So contravariant subtyping would be correct: –List a subtype of List But Java does not analyze interface definitions like this –Conservatively disallows this subtyping Number Integer

About the parameters So we have seen List and List are not subtype-related But there is subtyping “as expected” on the generic types themselves Example: If HeftyBag extends Bag, then –HeftyBag is a subtype of Bag –…

Where are we? Done: –Basics of generic types for classes and interfaces –Basics of bounding generics Now: –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