CMSC 330: Organization of Programming Languages Java Generics.

Slides:



Advertisements
Similar presentations
Comp 212: Intermediate Programming Lecture 18 – Java Generics By: Anupam Chanda.
Advertisements

Generic programming in Java
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
1 Generics, Type Safety, and Dynamic Data Structures.
Generic types for ArrayList Old Java (1.4 and older): ArrayList strings = new ArrayList(); strings.enqueue(“hello”); String word = (String) strings.get(0);
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.
Generic Programming Amit Shabtay. March 3rd, 2004 Object Oriented Design Course 2 The Problem Assume we have a nice Stack implementation. Our stack receives.
Generic Programming David Rabinowitz. June 14, 2006 Object Oriented Design Course 2 The problem Assume we have a nice Stack implementation. Our stack.
Topic 6 Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
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.
1 L40 Generics (2). 2 OBJECTIVES  To understand raw types and how they help achieve backwards compatibility.  To use wildcards when precise type information.
Interfaces besides classes, Java recognizes another type, an interface interface is used to completely shield off all implementation from the programmer.
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.
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.
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.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
CMSC 330: Organization of Programming Languages Polymorphism.
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.
Chapter 9: Polymorphism Coming up: Creating Objects Revisited.
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.
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.
Self Type Constructors Atsushi Igarashi Kyoto University Joint work with Chieri Saito 1.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Copyright © Curt Hill Generic Classes Template Classes or Container Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Generic Data Structures "Get your data structures correct first, and the rest of the program will write itself." - David Jones EE 422CGenerics 1.
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
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 & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
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.
Generic(Parameterized ) types Mehdi Einali Advanced Programming in Java 1.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
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.
UMBC CMSC 331 Java Review of objects and variables in Java.
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.
More on Java Generics Multiple Generic Types Bounded Generic Types
Chapter 20 Generic Classes and Methods
Java Generics.
Chapter 19 Generics Dr. Clincy - Lecture.
Generics (Parametric Polymorphism)
Polymorphism.
Generics 27-Nov-18.
Generic programming in Java
Comp 212: Intermediate Programming Lecture 18 – Java Generics
Generics 2-May-19.
Chapter 19 Generics.
COMP204 Bernhard Pfahringer (with input from Robi Malik)
Presentation transcript:

CMSC 330: Organization of Programming Languages Java Generics

CMSC 3302 An Integer Stack Implementation class Stack { class Entry { Integer elt; Entry next; Entry(Integer i, Entry n) { elt = i; next = n; } } Entry theStack; void push(Integer i) { theStack = new Entry(i, theStack); } Integer pop() throws EmptyStackException { if (theStack == null)‏ throw new EmptyStackException(); else { Integer i = theStack.elt; theStack = theStack.next; return i; }}}

CMSC 3303 Integer Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); Now we want a stack of Floats … or some objects …

CMSC 3304 Polymorphism Using Object class Stack { class Entry { Object elt; Entry next; Entry(Object i, Entry n) { elt = i; next = n; } } Entry theStack; void push(Object i) { theStack = new Entry(i, theStack); } Object pop() throws EmptyStackException { if (theStack == null)‏ throw new EmptyStackException(); else { Object i = theStack.elt; theStack = theStack.next; return i; }}}

CMSC 3305 New Stack Client Stack is = new Stack(); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = (Integer) is.pop(); Now Stacks are reusable –push() works the same –But now pop() returns an Object Have to downcast back to Integer Not checked until run-time

CMSC 3306 Polymorphism Subtyping is a kind of polymorphism –Sometimes called subtype polymorphism –Allows method to accept objects of many types We saw parametric polymorphism in OCaml –It’s polymorphism because polymorphic functions can be applied to many different types Ad-hoc polymorphism is overloading –Operator overloading in C++ –Method overloading in Java

CMSC 3307 Parametric Polymorphism (for Classes)‏ After Java 1.5 we can parameterize the Stack class by its element type Syntax: –Class declaration:class A {... } A is the class name, as before T is a type variable, can be used in body of class (...)‏ –Client usage declaration:A x; We instantiate A with the Integer type

CMSC 3308 class Stack { class Entry { ElementType elt; Entry next; Entry(ElementType i, Entry n) { elt = i; next = n; } } Entry theStack; void push(ElementType i) { theStack = new Entry(i, theStack); } ElementType pop() throws EmptyStackException { if (theStack == null)‏ throw new EmptyStackException(); else { ElementType i = theStack.elt; theStack = theStack.next; return i; }}} Parametric Polymorphism for Stack

CMSC 3309 Stack Client Stack is = new Stack (); Integer i; is.push(new Integer(3)); is.push(new Integer(4)); i = is.pop(); No downcasts Type-checked at compile time No need to duplicate Stack code for every usage –line i = is.pop(); can stay the same even if the type of is isn’t an integer in every path through the program

CMSC Parametric Polymorphism for Methods String is a subtype of Object – static Object id(Object x) { return x; } – static Object id(String x) { return x; } – static String id(Object x) { return x; } – static String id(String x) { return x; } Can’t pass an Object to 2 or 4 3 doesn’t type check Can pass a String to 1 but you get an Object back

CMSC Parametric Polymorphism, Again But id() doesn’t care about the type of x –It works for any type So parameterize the static method: static T id(T x) { return x; } Integer i = id(new Integer(3)); –Notice no need to instantiate id; compiler figures out the correct type at usage –The formal parameter has type T, the actual parameter has type Integer

CMSC Standard Library, and Java 1.5 (and later)‏ Part of Java 1.5 (called “generics”)‏ –Comes with replacement for java.util.* class LinkedList {...} class HashMap {... } interface Collection {... } –Excellent tutorial listed on references page But they didn’t change the JVM to add generics – How was that done?

CMSC Translation via Erasure Replace uses of type variables with Object –class A {...T x;... } becomes –class A {...Object x;... } Add downcasts wherever necessary –Integer x = A.get(); becomes –Integer x = (Integer) (A.get()); So why did we bother with generics if they’re just going to be removed? –Because the compiler still did type checking for us –We know that those casts will not fail at run time

CMSC Limitations of Translation Some type information not available at compile- time –Recall type variables T are rewritten to Object Disallowed, assuming T is type variable: –new T() would translate to new Object() (error)‏ –new T[n] would translate to new Object[n] (warning)‏ –Some casts/instanceofs that use T (Only ones the compiler can figure out are allowed)‏

CMSC Using with Legacy Code Translation via type erasure –class A becomes class A Thus class A is available as a “raw type” –class A {... } –class B { A x; } // use A as raw type Sometimes useful with legacy code, but... –Dangerous feature to use, plus unsafe –Relies on implementation of generics, not semantics

CMSC Polymorphism Quiz #1 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes floats and ints because the programmer provided two different versions of the function, one for each type int foo(int x) { return x+1; } float foo(float x) { return x+1.0; }

CMSC Polymorphism Quiz #2 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes Floats and Integers because both are subclasses of Numbers class Number { } class Float extends Number { } class Integer extends Number { } String foo(Number x)‏ { return x.toString(); }

CMSC Polymorphism Quiz #3 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes floats and ints because the function body does not perform any operation that constrains the type of x let foo x = x

CMSC Polymorphism Quiz #4 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc foo(x) takes Floats and Integers because the programmer used generics T foo(T x) { return x; }

CMSC Polymorphism Quiz #5 What kind of polymorphism? –Possible answers: subtype, parametric (classes or methods), or ad-hoc the constructor for class Foo takes Floats and Integers because the programmer used generics class Foo { Foo(T x) { } }

CMSC Subtyping and Arrays Java has one funny subtyping feature: –If S is a subtype of T, then –S[] is a subtype of T[]

CMSC Problem with Subtyping Arrays Program compiles without warning Java must generate run-time check at (1) to prevent (2)‏ –Type written to array must be subtype of array contents public class A {... } public class B extends A { void newMethod(); }... void foo(void) { B[] bs = new B[3]; A[] as; as = bs; // Since B[] subtype of A[] as[0] = new A(); // (1)‏ bs[0].newMethod(); // (2) Fails since not type B }

CMSC Subtyping for Generics Is Stack a subtype of Stack ? –We could have the same problem as with arrays –Thus Java forbids this subtyping Now consider the following method: –Not allowed to call count(x) where x has type Stack int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

CMSC int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { T e = i.next(); j++; } return j;} Solution I: Use Polymorphic Methods But requires a “dummy” type variable that isn’t really used for anything

CMSC Solution II: Wildcards Use ? as the type variable –Collection is “Collection of unknown” Why is this safe? –Using ? is a contract that you’ll never rely on having a particular parameter type –All objects subtype of Object, so assignment to e ok int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); j++; } return j; }

CMSC Legal Wildcard Usage Reasonable question: –Stack is not a subtype of Stack –Why is Stack a subtype of Collection ? Answer: –Wildcards permit “reading” but not “writing”

CMSC Example: Can read but cannot write int count(Collection c) { int j = 0; for (Iterator i = c.iterator(); i.hasNext(); ) { Object e = i.next(); c.add(e); // fails: Object is not ? j++; } return j; }

CMSC For Loops Java 1.5 has a more convenient syntax for this standard for loop –This loop will get the standard iterate and set e to each element of the list, in order int count(Collection c) { int j = 0; for (Object e : c)‏ j++; return j; }

CMSC More on Generic Classes Suppose we have classes Circle, Square, and Rectangle, all subtypes of Shape –Can we pass this method a Collection ? No, not a subtype of Collection –How about the following? void drawAll(Collection c) { for (Shape s : c)‏ s.draw(); } void drawAll(Collection c) { for (Shape s : c)‏ s.draw(); } // not allowed, assumes ? is Shape

CMSC Bounded Wildcards We want drawAll to take a Collection of anything that is a subtype of shape –this includes Shape itself –This is a bounded wildcard –We can pass Collection –We can safely treat s as a Shape void drawAll(Collection c) { for (Shape s : c)‏ s.draw(); }

CMSC Upper Bounded Wild Cards ? extends Shape actually gives an upper bound on the type accepted Shape is the upper bound of the wildcard Shape Circle Rectangle Square

CMSC Bounded Wildcards (cont’d)‏ Should the following be allowed? –No, because c might be a Collection of something that is not compatible with Rectangle –This code is forbidden at compile time void foo(Collection c) { c.add(new Rectangle()); }

CMSC Lower Bounded Wildcards Dual of the upper bounded wildcards ? super Rectangle denotes a type that is a supertype of Rectangle –T is included ? super Rectangle gives a lower bound on the type accepted Shape Circle Rectangle Square

CMSC Lower Bounded Wildcards (cont’d)‏ But the following is allowed: –Because c is a Collection of something that is always compatible with Circle void foo(Collection c) { c.add(new Circle()); c.add(new Rectangle()); // fails }

CMSC Bounded Type Variables You can also add bounds to regular type vars –This method can take a List of any subclass of Shape This addresses some of the reason that we decided to introduce wild cards Once again, this only works for methods T getAndDrawShape(List c) { c.get(1).draw(); return c.get(2); }