Chapter 22 Generic Programming. Chapter Goals To understand the objective of generic programming To be able to implement generic classes and methods To.

Slides:



Advertisements
Similar presentations
Linked List A linked list consists of a number of links, each of which has a reference to the next link. Adding and removing elements in the middle of.
Advertisements

Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Double-Linked Lists and Circular Lists
Copyright © 2013 by John Wiley & Sons. All rights reserved. HOW TO CREATE LINKED LISTS FROM SCRATCH CHAPTER Slides by Rick Giles 16 Only Linked List Part.
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.
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.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
Java Generics.
1 Lecture 24 ADT Part V (Linked List Using Iterator) Overview  Utility Classes.  List Iterator.  View of the List Iterator.  Adding to the Head of.
Fall 2007CS 2251 Lists and the Collection Interface Chapter 4.
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.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
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.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
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
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.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
Chapters (ArrayList / Generic)
LinkedList Many slides from Horstmann modified by Dr V.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Fifteen: An Introduction to Data Structures.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. An Introduction to Data Structures.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Chapter 16 Data Structures 1 ©2000, John Wiley & Sons, Inc. Horstmann/Java Essentials, 2/e Chapter 16 An Introduction to Data Structures.
Lecture Objectives  Linked list data structures:  Singly-linked (cont.)  Doubly-linked  Circular  Implementing the List interface as a linked list.
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.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
Copyright © 2014 by John Wiley & Sons. All rights reserved.1 Chapter 16 – Basic Data Structures.
Chapter 15 An Introduction to Data Structures. Chapter Goals To learn how to use the linked lists provided in the standard library To be able to use iterators.
List Interface and Linked List Mrs. Furman March 25, 2010.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Data Structures I Collection, List, ArrayList, LinkedList, Iterator, ListNode.
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 15 – An Introduction to Data Structures.
CS 46B: Introduction to Data Structures July 21 Class Meeting Department of Computer Science San Jose State University Summer 2015 Instructor: Ron Mak.
CSE 501N Fall ‘09 10: Introduction to Collections and Linked Lists 29 September 2009 Nick Leidenfrost.
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.
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.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by.
Slides by Donald W. Smith
Sixth Lecture ArrayList Abstract Class and Interface
Unit 1 Hadoop and big data
Chapter 20 An Introduction to Data Structures
Chapter 16 – Basic Data Structures
Introduction to Data Structures
Lecture 26: Advanced List Implementation
Chapter 15 – An Introduction to Data Structures
Generic programming in Java
Chapter 18 – Generic Classes
Dynamic Data Structures and Generics
Generics.
Chapter 19 Generics.
CSE 143 Lecture 21 Advanced List Implementation
Presentation transcript:

Chapter 22 Generic Programming

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 Continued

Chapter Goals To understand the relationship between generic types and inheritance To learn how to constrain type variables

Type Variables Generic programming: creation of programming constructs that can be used with many different types  In Java, achieved with inheritance or with type variables For example:  Type variables: Java's ArrayList (e.g. ArrayList )  Inheritance: LinkedList implemented in Section 20.2 can store objects of any class Continued

Type Variables Generic class: declared with a type variable E The type variable denotes the element type: public class ArrayList // could use "ElementType" instead of E { public ArrayList() {... } public void add(E element) {... }... } Continued

Type Variables Can be instantiated with class or interface types Cannot use a primitive type as a type variable Use corresponding wrapper class instead ArrayList ArrayList ArrayList // Wrong! ArrayList

Type Variables Supplied type replaces type variable in class interface Example: add in ArrayList has type variable E replaced with BankAccount : Contrast with LinkedList.add : public void add(BankAccount element) public void add(Object element)

Type Variables Increase Safety Type variables make generic code safer and easier to read Impossible to add a String into an ArrayList Continued

Type Variables Increase Safety 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

Syntax 22.1: Instantiating a Generic Class GenericClassName Example: ArrayList HashMap Purpose: To supply specific types for the type variables of a generic class

Self Check 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. 2.The binary search tree class in Chapter 21 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?

Answers 1. HashMap 2. It uses inheritance.

Implementing Generic Classes Example: simple generic class that stores pairs of objects The getFirst and getSecond retrieve first and second values of pair Pair result = new Pair<String, BankAccount >("Harry Hacker", harrysChecking); String name = result.getFirst(); BankAccount account = result.getSecond(); Continued

Implementing Generic Classes Example of use: return two values at the same time (method returns a Pair ) Generic Pair class requires two type variables public class Pair

Good Type Variable Names Type VariableName Meaning EElement type in a collection KKey type in a map VValue type in a map TGeneral type S, UAdditional general types

Class Pair public class Pair { public Pair(T firstElement, S secondElement) { first = firstElement; second = secondElement; } public T getFirst() { return first; } public S getSecond() { return second; } private T first; private S second; }

Turning LinkedList into a Generic Class public class LinkedList {... public E removeFirst() { if (first == null) throw new NoSuchElementException(); E element = first.data; first = first.next; return element; }... private Node first; Continued

Turning LinkedList into a Generic Class private class Node { public E data; public Node next; } }

Implementing Generic Classes Use type E when you receive, return, or store an element object Complexities arise only when your data structure uses helper classes If helpers are inner classes, no need to do anything special Helper types defined outside generic class need to become generic classes too public class ListNode

Syntax 22.2: Defining a Generic Class accessSpecifier class GenericClassName<TypeVariable1, TypeVariable2,...> { constructors methods fields } Example: public class Pair {... } Purpose: To define a generic class with methods and fields that depend on type variables

File LinkedList.java 001: import java.util.NoSuchElementException; 002: 003: /** 004: A linked list is a sequence of nodes with efficient 005: element insertion and removal. This class 006: contains a subset of the methods of the standard 007: java.util.LinkedList class. 008: */ 009: public class LinkedList 010: { 011: /** 012: Constructs an empty linked list. 013: */ 014: public LinkedList() 015: { 016: first = null; 017: } 018: Continued

File LinkedList.java 019: /** 020: Returns the first element in the linked list. the first element in the linked list 022: */ 023: public E getFirst() 024: { 025: if (first == null) 026: throw new NoSuchElementException(); 027: return first.data; 028: } 029: 030: /** 031: Removes the first element in the linked list. the removed element 033: */ 034: public E removeFirst() 035: { Continued

File LinkedList.java 036: if (first == null) 037: throw new NoSuchElementException(); 038: E element = first.data; 039: first = first.next; 040: return element; 041: } 042: 043: /** 044: Adds an element to the front of the linked list. element the element to add 046: */ 047: public void addFirst(E element) 048: { 049: Node newNode = new Node(); 050: newNode.data = element; 051: newNode.next = first; 052: first = newNode; 053: } Continued

File LinkedList.java 054: 055: /** 056: Returns an iterator for iterating through this list. an iterator for iterating through this list 058: */ 059: public ListIterator listIterator() 060: { 061: return new LinkedListIterator(); 062: } 063: 064: private Node first; 065: 066: private class Node 067: { 068: public E data; 069: public Node next; 070: } 071: Continued

File LinkedList.java 072: private class LinkedListIterator implements ListIterator 073: { 074: /** 075: Constructs an iterator that points to the front 076: of the linked list. 077: */ 078: public LinkedListIterator() 079: { 080: position = null; 081: previous = null; 082: } 083: 084: /** 085: Moves the iterator past the next element. the traversed element 087: */ 088: public E next() 089: { Continued

File LinkedList.java 090: if (!hasNext()) 091: throw new NoSuchElementException(); 092: previous = position; // Remember for remove 093: 094: if (position == null) 095: position = first; 096: else 097: position = position.next; 098: 099: return position.data; 100: } 101: 102: /** 103: Tests if there is an element after the iterator 104: position. true if there is an element after the 106: iterator position 107: */ Continued

File LinkedList.java 108: public boolean hasNext() 109: { 110: if (position == null) 111: return first != null; 112: else 113: return position.next != null; 114: } 115: 116: /** 117: Adds an element before the iterator position 118: and moves the iterator past the inserted element. element the element to add 120: */ 121: public void add(E element) 122: { 123: if (position == null) 124: { Continued

File LinkedList.java 125: addFirst(element); 126: position = first; 127: } 128: else 129: { 130: Node newNode = new Node(); 131: newNode.data = element; 132: newNode.next = position.next; 133: position.next = newNode; 134: position = newNode; 135: } 136: previous = position; 137: } 138: 139: /** 140: Removes the last traversed element. This method may 141: only be called after a call to the next() method. 142: */ Continued

File LinkedList.java 143: public void remove() 144: { 145: if (previous == position) 146: throw new IllegalStateException(); 147: 148: if (position == first) 149: { 150: removeFirst(); 151: } 152: else 153: { 154: previous.next = position.next; 155: } 156: position = previous; 157: } 158: Continued

File LinkedList.java 159: /** 160: Sets the last traversed element to a different 161: value. element the element to set 163: */ 164: public void set(E element) 165: { 166: if (position == null) 167: throw new NoSuchElementException(); 168: position.data = element; 169: } 170: 171: private Node position; 172: private Node previous; 173: } 174: }

File ListIterator.java 01: /** 02: A list iterator allows access of a position in a linked 03: list. This interface contains a subset of the methods 04: of the standard java.util.ListIterator interface. The 05: methods for backward traversal are not included. 06: */ 07: public interface ListIterator 08: { 09: /** 10: Moves the iterator past the next element. the traversed element 12: */ 13: E next(); 14: 15: /** 16: Tests if there is an element after the iterator 17: position. Continued

File ListIterator.java true if there is an element after the iterator 19: position 20: */ 21: boolean hasNext(); 22: 23: /** 24: Adds an element before the iterator position 25: and moves the iterator past the inserted element. element the element to add 27: */ 28: void add(E element); 29: 30: /** 31: Removes the last traversed element. This method may 32: only be called after a call to the next() method. 33: */ Continued

File ListIterator.java 34: void remove(); 35: 36: /** 37: Sets the last traversed element to a different 38: value. element the element to set 40: */ 41: void set(E element); 42: }

File ListTester.java 01: import java.util.LinkedList; 02: import java.util.ListIterator; 03: 04: /** 05: A program that demonstrates the LinkedList class 06: */ 07: public class ListTester 08: { 09: public static void main(String[] args) 10: { 11: LinkedList staff = new LinkedList (); 12: staff.addLast("Dick"); 13: staff.addLast("Harry"); 14: staff.addLast("Romeo"); 15: staff.addLast("Tom"); 16: Continued

File ListTester.java 17: // | in the comments indicates the iterator position 18: 19: ListIterator iterator = staff.listIterator(); // |DHRT 20: iterator.next(); // D|HRT 21: iterator.next(); // DH|RT 22: 23: // Add more elements after second element 24: 25: iterator.add("Juliet"); // DHJ|RT 26: iterator.add("Nina"); // DHJN|RT 27: 28: iterator.next(); // DHJNR|T 29: 30: // Remove last traversed element 31: 32: iterator.remove(); // DHJN|T 33: Continued

File ListTester.java 34: // Print all elements 35: 36: iterator = staff.listIterator(); 37: while (iterator.hasNext()) 38: { 39: String element = iterator.next(); 40: System.out.println(element); 41: } 42: } 43: }

File ListTester.java Output: Dick Harry Juliet Nina Tom

Self Check 3.How would you use the generic Pair class to construct a pair of strings "Hello" and "World" ? 4.What change was made to the ListIterator interface, and why was that change necessary?

Answers ListIterator is now a generic type. Its interface depends on the element type of the linked list. new Pair ("Hello", "World")

Generic Methods Generic method: method with a type variable Can be defined inside ordinary and generic classes A regular (non-generic) method: /** Prints all elements in an array of a the array to print */ public static void print(String[] a) { for (String e : a) System.out.print(e + " "); System.out.println(); } Continued

Generic Methods What if we want to print an array of Rectangle objects instead? public static void print(E[] a) { for (E e : a) System.out.print(e + " "); System.out.println(); }

Generic Methods When calling a generic method, you need not instantiate the type variables: The compiler deduces that E is Rectangle You can also define generic methods that are not static Rectangle[] rectangles =...; ArrayUtil.print(rectangles); Continued

Generic Methods 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[]

Syntax 22.1: Instantiating a Generic Class modifiers returnType methodName(parameters) { body } Example: public static void print(E[] a) {... } Purpose: To define a generic method that depends on type variables

Self Check 5.Exactly what does the generic print method print when you pass an array of BankAccount objects containing two bank accounts with zero balances? 6.Is the getFirst method of the Pair class a generic method?

Answers 5.The output depends on the definition of the toString method in the BankAccount class. 6.No–the method has no type parameters. It is an ordinary method in a generic class.

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; } Continued

Constraining Type Variables 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

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

Self Check 7.Declare a generic BinarySearchTree class with an appropriate type variable. 8.Modify the min method to compute the minimum of an array of elements that implements the Measurable interface of Chapter 11.

Answers 8. public class BinarySearchTree 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; }

Wildcard Types NameSyntaxMeaning Wildcard with lower bound? Extends BAny subtype of B Wildcard with upper bound? Super BAny supertype of B Unbounded wildcard?Any type

Wildcard Types can think of that declaration as a shorthand for static void reverse(List list) 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) Continued

Wildcard Types You can think of that declaration as a shorthand for static void reverse(List list)

Raw Types The virtual machine works with raw types, not with generic classes The raw type of a generic type is obtained by erasing the type variables Continued

Raw Types For example, generic class Pair turns into the following raw class: public class Pair { public Pair(Object firstElement, Object secondElement) { first = firstElement; second = secondElement; } public Object getFirst() { return first; } public Object getSecond() { return second; } private Object first; private Object second; }

Raw Types 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; } Continued

Raw Types Knowing about raw types helps you understand limitations of Java generics For example, you cannot replace type variables with primitive types To interface with legacy code, you can convert between generic and raw types

Self Check 9.What is the erasure of the print method in Section 22.3? 10.What is the raw type of the LinkedList class in Section 22.2?

Answers 10.The LinkedList class of Chapter 20. public static void print(Object[] a) { for (Object e : a) System.out.print(e + " "); System.out.println(); }