Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.

Slides:



Advertisements
Similar presentations
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. It is common to use two nested loops when filling or searching: for.
Advertisements

CHAPTER 12 GENERICS Introduction to java 1. Assignment 5 Solution See Eclipse.
Sadegh Aliakbary Sharif University of Technology Fall 2012.
Generic programming in Java
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 18 – Generic Classes.
Generics. DCS – SWC 2 Generics In many situations, we want a certain functionality to work for a variety of types Typical example: we want to be able.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Interfaces and Polymorphism.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 3 Implementing Classes. Instance Variables Instance variables store the data of an object; the fields of an object. Instance of a class: an object.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Chapter 9 – Inheritance Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 2 – An Introduction to Objects and Classes Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Java Generics.
Chapter 7 – Arrays.
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.
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.
CS221 - Computer Science II Polymorphism 1. CS221 - Computer Science II Polymorphism 2 Outline  Explanation of polymorphism.  Using polymorphism to.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 17 Animated Version Generics and Type Safety.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Java Generics.
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.
Effective Java: Generics Last Updated: Spring 2009.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Chapters (ArrayList / Generic)
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Working with arrays (we will use an array of double as example)
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 10 - Interfaces.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 19 Generics.
COMP 121 Week 8: Generic Collections. Objectives To understand type variables and how they are used in generic programming To be able to implement and.
©SoftMoore ConsultingSlide 1 Generics “Generics constitute the most significant change in the Java programming language since the 1.0 release.” – Cay Horstmann.
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Chapter 22 Generic Programming. Chapter Goals To understand the objective of generic programming To be able to implement generic classes and methods To.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. 1.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 15 – An Introduction to Data Structures.
When constructing a two-dimensional array, specify how many rows and columns are needed: final int ROWS = 3; final int COLUMNS = 3; String[][] board =
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Three - Implementing Classes.
Array: Sequence of values of the same type Construct array: new double[10] Store in variable of type double[] : double[] data = new double[10]; When array.
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.
12-CRS-0106 REVISED 8 FEB 2013 CSG2H3 Object Oriented Programming.
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.
Sixth Lecture ArrayList Abstract Class and Interface
Lecture 3 John Woodward.
Unit 1 Hadoop and big data
Chapter 20 Generic Classes and Methods
Chapter Three - Implementing Classes
Chapter 19 Generics Dr. Clincy - Lecture.
Generic programming in Java
Chapter 18 – Generic Classes
Chapter 19 Generics.
Chapter 21 Generics.
Generics.
Chapter 19 Generics Jung Soo (Sue) Lim Cal State LA.
Chapter 21 Generics.
Chapter 19 Generics.
Chapter 19 Generics.
Presentation transcript:

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter Goals To understand the objective of generic programming To be able to implement generic classes and methods To understand the execution of generic methods in the virtual machine To know the limitations of generic programming in Java

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic Classes and Type Parameters Generic programming: creation of programming constructs that can be used with many different types In Java, achieved with type parameters or with inheritance Type parameter example: Java's ArrayList (e.g. ArrayList ) Inheritance example: LinkedList implemented in Section 15.2 can store objects of any class Generic class: declared with one or more type parameters A type parameter for ArrayList denotes the element type: public class ArrayList { public ArrayList() {... } public void add(E element) {... }... }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Parameters Can be instantiated with class or interface type: ArrayList Cannot use a primitive type as a type variable: ArrayList // Wrong! Use corresponding wrapper class instead: ArrayList

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Parameters Supplied type replaces type variable in class interface Example: add in ArrayList has type variable E replaced with BankAccount : public void add(BankAccount element) Contrast with LinkedList.add from Chapter 15 : public void add(Object element)

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Parameters Increase Safety Type parameters make generic code safer and easier to read Impossible to add a String into an ArrayList Can add a String into a LinkedList intended to hold bank accounts ArrayList accounts1 = new ArrayList (); LinkedList accounts2 = new LinkedList(); // Should hold BankAccount objects accounts1.add("my savings"); // Compile-time error accounts2.add("my savings"); // Not detected at compile time... BankAccount account = (BankAccount) accounts2.getFirst(); // Run-time error

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.1 The standard library provides a class HashMap with key type K and value type V. Declare a hash map that maps strings to integers. Answer: HashMap

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.2 The binary search tree class in Chapter 16 is an example of generic programming because you can use it with any classes that implement the Comparable interface. Does it achieve genericity through inheritance or type variables? Answer: It uses inheritance.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Implementing Generic Classes Example: simple generic class that stores pairs of objects such as: Pair result = new Pair ("Harry Hacker", harrysChecking); Methods getFirst and getSecond retrieve first and second values of pair: String name = result.getFirst(); BankAccount account = result.getSecond(); Example of use: return two values at the same time (method returns a Pair ) Generic Pair class requires two type parameters, one for each element type enclosed in angle brackets: public class Pair

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Good Type Variable Names Type VariableName Meaning E Element type in a collection K Key type in a map V Value type in a map T General type S, U Additional general types

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Class Pair public class Pair { private T first; private S second; public Pair(T firstElement, S secondElement) { first = firstElement; second = secondElement; } public T getFirst() { return first; } public S getSecond() { return second; } }

Syntax 17.1 Declaring a Generic Class Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Continued ch17/pair/Pair.java 1 /** 2 This class collects a pair of elements of different types. 3 */ 4 public class Pair 5 { 6 private T first; 7 private S second; 8 9 /** 10 Constructs a pair containing two given elements. firstElement the first element secondElement the second element 13 */ 14 public Pair(T firstElement, S secondElement) 15 { 16 first = firstElement; 17 second = secondElement; 18 } 19

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/pair/Pair.java (cont.) 20 /** 21 Gets the first element of this pair. the first element 23 */ 24 public T getFirst() { return first; } /** 27 Gets the second element of this pair. the second element 29 */ 30 public S getSecond() { return second; } public String toString() { return "(" + first + ", " + second + ")"; } 33 }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Continued ch17/pair/PairDemo.java 1 public class PairDemo 2 { 3 public static void main(String[] args) 4 { 5 String[] names = { "Tom", "Diana", "Harry" }; 6 Pair result = firstContaining(names, "a"); 7 System.out.println(result.getFirst()); 8 System.out.println("Expected: Diana"); 9 System.out.println(result.getSecond()); 10 System.out.println("Expected: 1"); 11 } 12

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/pair/PairDemo.java (cont.) 13 /** 14 Gets the first String containing a given string, together 15 with its index. strings an array of strings sub a string a pair (strings[i], i) where strings[i] is the first 19 strings[i] containing str, or a pair (null, -1) if there is no 20 match. 21 */ 22 public static Pair firstContaining( 23 String[] strings, String sub) 24 { 25 for (int i = 0; i < strings.length; i++) 26 { 27 if (strings[i].contains(sub)) 28 { 29 return new Pair (strings[i], i); 30 } 31 } 32 return new Pair (null, -1); 33 } 34 } Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. ch17/pair/PairDemo.java (cont.) Program Run : Diana Expected: Diana 1 Expected: 1

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.3 How would you use the generic Pair class to construct a pair of strings "Hello" and "World" ? Answer: new Pair ("Hello", "World")

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.4 What is the difference between an ArrayList > and a Pair, Integer> ? Answer: An ArrayList > contains multiple pairs, for example [(Tom, 1), (Harry, 3)]. A Pair, Integer> contains a list of strings and a single integer, such as ([Tom, Harry], 1).

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic Methods Generic method: method with a type variable Can be defined inside non-generic classes Example: Want to declare a method that can print an array of any type: public class ArrayUtil { /** Prints all elements in an a the array to print */ public static void print(T[] a) {... } }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic Methods Often easier to see how to implement a generic method by starting with a concrete example; e.g. print the elements in an array of strings: public class ArrayUtil { public static void print(String[] a) { for (String e : a) System.out.print(e + " "); System.out.println(); }... }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic Methods In order to make the method into a generic method: Replace String with a type parameter, say E, to denote the element type Supply the type parameters between the method's modifiers and return type public static void print(E[] a) { for (E e : a) System.out.print(e + " "); System.out.println(); }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Generic Methods When calling a generic method, you need not instantiate the type variables: Rectangle[] rectangles =...; ArrayUtil.print(rectangles); The compiler deduces that E is Rectangle You can also define generic methods that are not static You can even have generic methods in generic classes Cannot replace type variables with primitive types e.g.: cannot use the generic print method to print an array of type int[]

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Syntax 17.2 Defining a Generic Method

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.5 Exactly what does the generic print method print when you pass an array of BankAccount objects containing two bank accounts with zero balances? Answer: The output depends on the definition of the toString method in the BankAccount class.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.6 Is the getFirst method of the Pair class a generic method? Answer: No — the method has no type parameters. It is an ordinary method in a generic class.

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Constraining Type Variables Type variables can be constrained with bounds: public static E min(E[] a) { E smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].compareTo(smallest) < 0) smallest = a[i]; return smallest; } Can call min with a String[] array but not with a Rectangle[] array Comparable bound necessary for calling compareTo Otherwise, min method would not have compiled

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Constraining Type Variables Very occasionally, you need to supply two or more type bounds: extends, when applied to type variables, actually means “extends or implements” The bounds can be either classes or interfaces Type variable can be replaced with a class or interface type

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.7 How would you constrain the type parameter for a generic BinarySearchTree class? Answer: public class BinarySearchTree

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.8 Modify the min method to compute the minimum of an array of elements that implements the Measurable interface of Chapter 9. Answer: public static E min(E[] a) { E smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].getMeasure() < smallest.getMeasure()) < 0) smallest = a[i]; return smallest; }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Wildcard Types NameSyntaxMeaning Wildcard with lower bound ? extends B Any subtype of B Wildcard with higher bound ? super B Any supertype of B Unbounded wildcard ? Any type

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Wildcard Types public void addAll(LinkedList other) { ListIterator iter = other.listIterator(); while (iter.hasNext()) add(iter.next()); } public static > E min(E[] a) static void reverse(List list) You can think of that declaration as a shorthand for static void reverse(List list)

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure The virtual machine erases type parameters, replacing them with their bounds or Object s For example, generic class Pair turns into the following raw class: public class Pair { private Object first; private Object second; public Pair(Object firstElement, Object secondElement) { first = firstElement; second = secondElement; } public Object getFirst() { return first; } public Object getSecond() { return second; } } Continued

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure Same process is applied to generic methods: public static Comparable min(Comparable[] a) { Comparable smallest = a[0]; for (int i = 1; i < a.length; i++) if (a[i].compareTo(smallest) < 0) smallest = a[i]; return smallest; }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure Knowing about raw types helps you understand limitations of Java generics For example, trying to fill an array with copies of default objects would be wrong: public static void fillWithDefaults(E[] a) { for (int i = 0; i < a.length; i++) a[i] = new E(); // ERROR } Type erasure yields: public static void fillWithDefaults(Object[] a) { for (int i = 0; i < a.length; i++) a[i] = new Object(); // Not useful }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure To solve this particular problem, you can supply a default type: public static void fillWithDefaults(E[] a, E defaultValue) { for (int i = 0; i < a.length; i++) a[i] = defaultValue; }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure You cannot construct an array of a generic type: public class Stack { private E[] elements;... public Stack() { elements = new E[MAX_SIZE]; // Error } Because the array construction expression new E[] would be erased to new Object[]

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Type Erasure One remedy is to use an array list instead: public class Stack { private ArrayList elements;... public Stack() { elements = new ArrayList (); // Ok }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check 17.9 What is the erasure of the print method in Section 17.3? Answer: public static void print(Object[] a) { for (Object e : a) System.out.print(e + " "); System.out.println(); }

Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Self Check Could the Stack example be implemented as follows? public class Stack { private E[] elements;... public Stack() { elements = (E[]) new Object[MAX_SIZE]; }... } Answer: This code compiles (with a warning), but it is a poor technique. In the future, if type erasure no longer happens, the code will be wrong. The cast from Object[] to String[] will cause a class cast exception.