JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy.

Slides:



Advertisements
Similar presentations
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 17: Type Conversions,
Advertisements

CS324e - Elements of Graphics and Visualization A Little Java A Little Python.
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
1 ADT and Data Structure Example Generics / Parameterized Classes Using a Set Implementing a Set with an Array Example: SetADT interface Example: ArraySet.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Java Generics.
Lecture 27 Exam outline Boxing of primitive types in Java 1.5 Generic types in Java 1.5.
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 Java Object Model Part 1. 2 Type Definition: set of values – a set of values and set of operations –a set of operations that can be applied to those.
CS102 Data Types in Java CS 102 Java’s Central Casting.
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.
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.
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.
Types in programming languages What are types, and why do we need them? Types in programming languages1.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
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-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.
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.
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.
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
ArrayList, Multidimensional Arrays
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Generics CSCI 201L Jeffrey Miller, Ph.D. HTTP :// WWW - SCF. USC. EDU /~ CSCI 201 USC CSCI 201L.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
GENERICS. Generics  Classes and methods can have a type parameter (actually, more than one).  The type parameter can be any reference (class) type.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 5 Generic.
G ENERICS I N J AVA BY: Ankit Goyal Sankalp Singh.
Generics CompSci 230 S Software Construction.
Types in programming languages1 What are types, and why do we need them?
Introduction to Generics
Lecture 4 Generic programming Advanced Java Programming 1 dr hab. Szymon Grabowski dr inż. Wojciech Bieniecki
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
©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.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Types and Interfaces COMP.
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.
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.
Interfaces & Sub-types Weiss sec Scenario Instructor says: “Implement a class IntegerMath with two methods pow and fact with the following signatures:
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
CS/ENGRD 2110 SPRING 2016 Lecture 6: Consequence of type, casting; function equals 1.
April 13, 1998CS102-02Lecture 3-1 Data Types in Java CS Lecture 3-1 Java’s Central Casting.
Java Generics.
Chapter 20 Generic Classes and Methods
Java Generics Lecture 14 CS2110 – Fall 2016
Java Generics Lecture 17 CS2110 – Spring 2017
Java Generics.
Java Generics Lecture 22 CS2110 – Fall 2018
Generic programming in Java
Java Generics Lecture 22 CS2110 – Fall 2018
ArrayLists 22-Feb-19.
Web Design & Development Lecture 6
Presentation transcript:

JAVA GENERICS Lecture 16 CS2110 – Spring 2016 Photo credit: Andrew Kennedy

Textbook and Homework Generics: Appendix B Generic types we discussed: Chapters 1-3, 15 Useful tutorial: docs.oracle.com/javase/tutorial/extra/generics/index.html 2

Early versions of Java lacked generics… 3 Java Collections interface Collection { /* Return true if the collection contains o */ boolean contains(Object o); /* Add o to the collection; return true if *the collection is changed. */ boolean add(Object o); /* Remove o fromthe collection; return true if * the collection is changed. */ boolean remove(Object o);... }

4 Java Collections Collection c =... c.add(“Hello”) c.add(“World”);... for (Object o : c) { String s = (String) o; System.out.println(s.length + “ : “ + s.length()); } The lack of generics was painful when using collections, because programmers had to insert manual casts into their code... … and people often made mistakes!

5 Using Java Collections String [] a =... a[0] = (“Hello”) a[1] = (“World”);... for (String s : a) { System.out.println(s); } This limitation was especially awkward because built- in arrays do not have the same problem! So, in the late 1990s Sun Microsystems initiated a design process to add generics to the language...

6 Arrays → Generics Object[] a =... String[] a =... Integer[] a =... Button[] a =... One can think of the array “brackets” as a kind of parameterized type: a type-level function that takes one type as input and yields another type as output We should be able to do the same thing with object types generated by classes!

7 Proposals for adding Generics to Java PolyJPizza/GJ LOOJ

With generics, the Collection interface becomes... 8 Generic Collections interface Collection { /* Return true if the collection contains x */ boolean contains(T x); /* Add x to the collection; return true if *the collection is changed. */ boolean add(T x); /* Remove x fromthe collection; return true if * the collection is changed. */ boolean remove(T x);... }

9 Using Java Collections Collection c =... c.add(“Hello”) c.add(“World”);... for (String s : c) { System.out.println(s.length + “ : “ + s.length()); } With generics, no casts are needed... … and mistakes (usually) get caught!

10 Static Type checking Collection c =... c.add(“Hello”) /* Okay */ c.add(1979); /* Illegal: static error! */ The compiler can automatically detect uses of collections with incorrect types... Generally speaking, Collection behaves like the parameterized type Collection where all occurrences of T have been substituted with String.

Subtyping extends naturally to generic types. 11 Subtyping interface Collection {... } interface List extends Collection {... } class LinkedList implements List {... } class ArrayList implements List {... } /* The following statements are all legal. */ List l = new LinkedList (); ArrayList a = new ArrayList (); Collection c = a; l = a c = l;

String is a subtype of object so......is LinkedList a subtype of LinkedList ? 12 Subtyping LinkedList ls= new LinkedList (); LinkedList lo= new LinkedList (); lo= ls; //Suppose this is legal lo.add(2110); //Type-checks: Integer subtype Object String s = ls.get(0); //Type-checks: ls is a List //UH OH: What does s point to, and what is its type?!?!?! But what would happen at run-time if we were able to actually execute this code?

Java’s type system allows the analogous rule for arrays :-/ 13 Array Subtyping String[] as = new String[10]; Object[] ao= new Object[10]; ao = as; //Type-checks: considered outdated design ao[0] = 2110; //Type-checks: Integer subtype Object String s =as[0]; //Type-checks: as is a String array What happens when this code is run? It throws an ArrayStoreException!

Suppose we want to write a helper method to print every value in a Collection. 14 Printing Collections void print(Collection c) { for (Object x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c); /* Illegal: Collection is not a * subtype of Collection ! */

To get around this problem, Java’s designers added wildcards to the language 15 Wildcards void print(Collection c) { for (Object x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c); /* Legal! */ One can think of Collection as a “Collection of some unknown type of values”.

Note that we cannot add values to collections whose types are wildcards Wildcards void doIt(Collection c) { c.add(42); /* Illegal! */ }... Collection c =... doIt(c); /* Legal! */ 42 can be added to Collection but c could be a Collection of anything, not just supertypes of Integer

Sometimes it is useful to know some information about a wildcard. Can do this by adding bounds Bounded Wildcards void doIt(Collection c) { c.add(42); /* Legal! */ }... Collection c =... doIt(c); /* Legal! */ Collection c =... doIt(c); /* Illegal! */ Now c can only be a Collection of some supertype of Integer, and 42 can be added to any such Collection “? super” is useful for when you are only giving values to the object, such as putting values into a Collection

“? extends” is useful for when you are only receiving values from the object, such as getting values out of a Collection 18 Bounded Wildcards void doIt(Collection c) { for (Shape s : c) s.draw(); }... Collection c =... doIt(c); /* Legal! */ Collection c =... doIt(c); /* Illegal! */

Wildcards can be nested. The following receives Collections from an Iterable and then gives floats to those Collections. 19 Bounded Wildcards void doIt(Iterable > cs) { for(Collection c : cs) c.add(0.0f); }... List > l =... doIt(l); /* Legal! */ Collection > c =... doIt(c); /* Legal! */ Iterable > i =... doIt(i); /* Illegal! */ ArrayList > a =... doIt(a); /* Legal! */

Returning to the printing example, another option would be to use a method-level type parameter Generic Methods void print(Collection c) {// T is a type parameter for (T x : c) { System.out.println(x); }... Collection c =... c.add(42); print(c); /* More explicitly: this. print(c) */ But wildcards are preferred when just as expressive.

Suppose we want to concatenate a whole list of lists into one list. We want the return type to depend on what the input type is. 21 Concatenating Lists List flatten(List > ls) { List flat = new ArrayList (); for (List l : ls) flat.addAll(l); return flat; }... List > is =... List i = flatten(is); List > ss =... List s = flatten(ss);

Suppose we need two parameters to have similar types. 22 Replacing Elements void replaceAll(List ts, T x, T y) { for (int i = 0; i < ts.size(); i++) if (Objects.equals(ts.get(i), x)) ts.set(i, y); } Note that we are both receiving values from ts and giving values to ts, so we can’t use a wildcard.

The Comparable interface declares a method for comparing one object to another. 23 Interface Comparable interface Comparable { /* Return a negative number, 0, or positive number * depending on whether this is less than, * equal to, or greater than that */ int compareTo(T that); } Integer, Double, Character, and String are all Comparable with themselves

Suppose we want to look up a value in a sorted list 24 Binary Search >//bounded type parameter int indexOf(List sorted, T x) { // no null values int min = 0; int max = l.size(); while (min < max) { int guess = (min + max) / 2; int comparison = x.compareTo(l.get(guess)); if (comparison < 0) max = guess; else if (comparison == 0) return guess; else min = guess + 1; return -1; }