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

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

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

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

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331 Software Design and Implementation. Lecture 14 Generics 2

CSE 331. Generics (Parametric Polymorphism)

CS108, Stanford Handout #8. Java Generics

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

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

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

CSE 331 Software Design and Implementation. Lecture 15 Generics 2

Software Engineering. Prof. Agostino Poggi

Photo credit: Andrew Kennedy JAVA GENERICS

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

Java Generics -- an introduction. Based on

CITS1001 week 4 Grouping objects

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

CSCE 314 Programming Languages

CSE 331 Software Design & Implementation

301AA - Advanced Programming [AP-2017]

Problems. Java Generics. Example. Example. Often you need the same behavior for different kind of classes

1.1. Annotations History Lesson - C/C++

Inheritance. Improving Structure with Inheritance. Dr. Siobhán Drohan Mairead Meagher. Produced by:

Today's Agenda. > To give a practical introduction to data structures. > To look specifically at Lists, Sets, and Maps

The collections interfaces

301AA - Advanced Programming [AP-2017]

Parametric polymorphism and Generics

Outline of lecture. i219 Software Design Methodology 6. Object oriented programming language 3. Kazuhiro Ogata (JAIST)

Improving structure with inheritance. Main concepts to be covered. The DoME example. DoME objects. DoME classes. DoME object model

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

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

CMSC 132: Object-Oriented Programming II. Generic Programming. Department of Computer Science University of Maryland, College Park

Advanced Topics in Java and on Security in Systems Effective Generics. Eirik Eltvik 26 th of February 2007

Announcements. Java Graphics. Exceptions. Java Odds & Ends

Exercise 8 Parametric polymorphism November 18, 2016

Objects and Iterators

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

CMSC 132: Object-Oriented Programming II

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

CMSC 202. Containers

Java 5 New Language Features

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

CS 302: Introduction to Programming in Java. Lecture 12

Introduction to Computer Science I

DM550 / DM857 Introduction to Programming. Peter Schneider-Kamp

Tony Valderrama, SIPB IAP 2010

Array Based Lists. Collections

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

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

Generics. IRS W-9 Form

CSE 331 Software Design and Implementation. Lecture 13 Generics 1

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

CS 211: Using ArrayList, Implementing Arraylist

Today: Sorting algorithms: why? Insertion Sort. Inversions. CS61B Lecture #26. Last modified: Sun Oct 22 18:22: CS61B: Lecture #26 1

ABSTRACT DATA TYPES: COLLECTIONS, LISTS, SETS, MAP, QUEUES. Thursday, June 30, 2011

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

Rules and syntax for inheritance. The boring stuff

Binghamton University. CS-140 Fall Dynamic Types

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Computational Expression

Generics method and class definitions which involve type parameters.

Collections, Maps and Generics

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

CSE 331 Software Design & Implementation

Big O & ArrayList Fall 2018 Margaret Reid-Miller

Comp215: Thinking Generically

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

Today: Sorting algorithms: why? Insertion Sort. Inversions. CS61B Lecture #26. Last modified: Wed Oct 24 13:43: CS61B: Lecture #26 1

1.00/ Lecture 8. Arrays-1

First Name Last Name ID#

CMSC 202H. Containers and Iterators

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Arrays and ArrayLists. David Greenstein Monta Vista High School

Java: exceptions and genericity

CS 211: Using ArrayList, Implementing Arraylist

The ArrayList class CSC 123 Fall 2018 Howard Rosenthal

Lecture #23: Conversion and Type Inference

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

AP CS Unit 7: Interfaces Exercises Assume all code compiles unless otherwise suggested.

Computer Science 210 Data Structures Siena College Fall 2018

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

CS61B Lecture #19. Last modified: Mon Oct 13 12:02: CS61B: Lecture #19 1

Generics and Type Safety. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

publicvoid set(objectobject){ this. object =object;} public Objectget(){ return object;}

Binghamton University. CS-140 Fall Interfaces

Exercise 8 Parametric polymorphism November 17, 2017

Generalized Code. Fall 2011 (Honors) 2

Arrays. CSE 142, Summer 2002 Computer Programming 1.

CSE 1223: Introduction to Computer Programming in Java Chapter 6 ArrayLists

CSE 143 Lecture 14. Sorting

COURSE 5 PROGRAMMING III OOP. JAVA LANGUAGE

generic programming alberto ferrari university of parma

Polymorphism (generics)

CS61B Lecture #17. Administrative: Need alternative test time? Make sure you send me mail.

Announcements. Java Review. More Announcements. Today. Assembly Language. Machine Language

Module 11. Collections and Iterators. Adapted from Absolute Java, Rose Williams, Binghamton University

Outline. runtime of programs algorithm efficiency Big-O notation List interface Array lists

Java Design Goals. Lecture 32: Java. Java Original implementations slow! Exceptions & Subtyping. - void method readfiles() throws IOException {...}!

Transcription:

CS61B Lecture #24 Today: Java support for generic programming Readings for today: A Java Reference, Chapter 10. Readings for Monday: Data Structures, 6.4. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 1

The Old Days Java library types such as List didn t used to be parameterized. All Lists were lists of Objects. So you d write things like this: for (int i = 0; i < L.size (); i += 1) { String s = (String) L.get (i);... That is, must explicitly cast result of L.get (i) to let the compiler know what it is. Also, when calling L.add(x), was no check that you put only Strings into it. So, newest release attempts to alleviate these perceived problems by introducing parameterized types, like List<String>. Unfortunately, it is not as simple as one might think. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 2

Basic Parameterization From the definitions of ArrayList and Map in java.util: public class ArrayList<Item> implements List<Item> { public Item get (int i) {... public boolean add (Item x) {...... public interface Map<Key, Value> { Value get (Key x);... First occurrence of Item, Key, and Value introduce formal type parameters, whose value (a reference type) in effect gets substituted for all the other occurrences of Item, Key, or Value when ArrayList or Map is called (as in ArrayList<String>, or ArrayList<int[]>, or Map<String, List<Particle>>). Can also say that you don t care what a type parameter is (wildcards): /** Number of items in C that are equal to X. */ static int frequency (Collection<?> c, Object x) {... Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 3

Parameters on Methods Functions (methods) may also be parameterized by type. Example of use from java.util.collections: /** A read-only list containing just ITEM. */ static <T> List<T> singleton (T item) {... In this case, compiler figures out T without help when you call singleton(x) by looking at the type of x. Another example (from java.util.collections): /** An unmodifiable empty list. */ static <T> List<T> emptylist () {... Here, a call to emptylist() would not contain enough information, so instead we write, e.g., Collections.<Particle>emptySet (), to tell the compiler that T is Particle. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 4

Type Bounds Sometimes, your program needs to ensure that a particular type parameter is replaced only by a subtype (or supertype) of a particular type (sort of like specifying the type of a type. ). For example, class NumericSet<T extends Number> extends HashSet<T> { /** My minimal element */ T min () {...... Requires that all type parameters to NumbericSet must be subtypes of Number (the type bound ). T can either extend or implement the bound, as appropriate. Another example: /** Set all elements of L to X. */ static <T> void fill (List<? super T> L, T x) {... means that L can be a List<Q> as long as T is a subtype of (extends or implements) Q. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 5

Type Bounds (II) And one more: /** Search sorted list L for KEY, returning either its position (if * present), or k-1, where k is where KEY should be inserted. */ static <T> int binarysearch(list<? extends Comparable<? super T>> L, T key) Here, the items of L have to have a type that is comparable to T s or some supertype of T. Does L have to be able to contain the value key? Why does this make sense? Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 6

Dirty Secrets Behind the Scenes Java s design for parameterized types was constrained by a desire for backward compatibility. Actually, when you write class Foo<T> { T x; T mogrify (T y) {... Java gives really gives you Foo<Integer> q = new Foo<Integer>(); Integer r = q.mogrify (s); class Foo { Object x; Foo q = new Foo(); Object mogrify (Object y) {... Integer r = (Integer) q.mogrify ((Integer) s); That is, it supplies the casts automatically, and also throws in some additional checks. If it can t guarantee that all those casts will work, gives you a warning about unsafe constructs. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 7

Limitations Because of Java s design choices, are some limitations to generic programming: Since all kinds of Foo or List are really the same, L instanceof List<String> will be true when L is a List<Integer>. Inside, e.g., class Foo, you cannot write new T (), new T[], or x instanceof T. Primitive types are not allowed as type parameters. Can t have ArrayList<int>, just ArrayList<Integer>. Fortunately, automatic boxing and unboxing makes this substitution easy: int sum (ArrayList<Integer> L) { int N; N = 0; for (int x : L) { N += x; return N; Unfortunately, boxing/unboxing have significant costs. Last modified: Fri Oct 19 19:33:03 2012 CS61B: Lecture #24 8