27137655705178acd2eba579b5af0f3e.ppt
- Количество слайдов: 62
Java Methods Object-Oriented Programming and Data Structures 3 rd AP edition Maria Litvin ● Gary Litvin map. put(20, "Chapter"); The Java Collections Framework Copyright © 2015 by Maria Litvin, Gary Litvin, and Skylight Publishing. All rights reserved. 1
Objectives: • Learn a subset of the Java collections framework • Practice working on a realistic software project as a team 2
Overview • Framework (in software): a general system of components and architectural solutions that provides development tools to programmers for use with a relatively wide range of applications. • Collection: (hmm. . . ) any collection of elements 3
Overview (cont’d) • Collection, Iterator • Lists, List. Iterator Ø Ø Ø List Array. List Linked. List • Stack • Queue, Priority. Queue • Sets Ø Ø Ø Set Tree. Set Hash. Set • Maps Ø Ø Ø Map Tree. Map Hash. Map All these interfaces and classes are part of the java. util package. Names of interfaces are in italics. 4
Overview (cont’d) 5
Overview (cont’d) • A collection holds references to objects (but we say informally that it “holds objects”). • A collection can contain references to two equal objects (a. equals(b)) as well as two references to the same object (a == b). • An object can belong to several collections. • An object can change while in a collection (unless it is immutable). 6
Overview (cont’d) • Starting with Java 5, a collection holds objects of a specified type. A collection class’s or interface’s definition takes object type as a parameter: Ø Ø Collection<E> List<E> Stack<E> Set<E> Because collections work with different types, these are called generic collections or generics • A map takes two object type parameters: Ø Map<K, V> 7
Collection, Iterator «interface» Iterator «interface» Collection • Collection interface represents any collection. • An iterator is an object that helps to traverse the collection (process all its elements in sequence). • A collection supplies its own iterator(s), (returned by collection’s iterator method); the traversal sequence depends on the collection. 8
Collection<E> Methods boolean is. Empty ( ) int size ( ) boolean contains (Object obj) boolean add (E obj) boolean remove (E obj) Iterator<E> iterator ( ) //. . . other methods «interface» Iterator «interface» Collection Supplies an iterator for this collection 9
Iterator<E> Methods «interface» Iterator boolean has. Next ( ) E next ( ) void remove ( ) «interface» Collection What’s “next” is determined by a particular collection Removes the last visited element 10
Iterator “For Each” Loop Collection<String> words = new Array. List<String>(); . . . for (String word : words) { <. . . process word > } Iterator<String> iter = words. iterator( ); while (iter. has. Next ( )) { String word = iter. next ( ); <. . . process word > } A “for each” loop is a syntactic shortcut that replaces an iterator 11
Lists, List. Iterator • A list represents a collection in which all elements are numbered by indices: a 0, a 1, . . . , an-1 • java. util: Ø Ø Ø List interface Array. List Linked. List • List. Iterator is an extended iterator, specific for lists (List. Iterator is a subinterface of Iterator) 12
Lists (cont’d) «interface» Collection «interface» Iterator «interface» List Array. List Linked. List «interface» Set etc. 13
List<E> Methods «interface» Iterator «interface» Collection «interface» List. Iterator «interface» List // All Collection<E> methods, plus: E get (int i) E set (int i, E obj) void add (int i, E obj) E remove (int i) int index. Of (Object obj) List. Iterator<E> list. Iterator (int i) These methods are familiar from Array. List, which implements List Returns a List. Iterator that starts iterations at index i 14
List. Iterator<E> Methods «interface» Iterator «interface» Collection «interface» List. Iterator «interface» List // The three Iterator<E> methods, plus: int next. Index ( ) boolean has. Previous ( ) Can traverse the E previous ( ) list backward int previous. Index ( ) void add (E obj) Can add elements to the list (inserts void set (E obj) after the last visited element) Can change elements (changes the last visited element) 15
List. Iterator “Cursor” Positioning iter. add(obj); (Reverse links not shown) 16
«interface» Iterator Array. List «interface» List. Iterator «interface» List Array. List Linked. List • Represents a list as a dynamic array (array that is resized when full) • Provides random access to the elements a 0 a 1 a 2 . . . an-1 • Implements all the methods of List<E> 17
«interface» List «interface» Iterator Linked. List «interface» List. Iterator Array. List Linked. List • Represents a list as a doubly-linked list with a header node (Chapter 21) header a 0 a 1 a 2 . . . an-1 • Implements all the methods of List<E> 18
Linked. List (cont’d) «interface» Iterator «interface» List Array. List Linked. List • Additional methods specific to Linked. List: void add. First (E obj) void add. Last (E obj) E get. First ( ) E get. Last ( ) E remove. First ( ) E remove. Last ( ) 19
Array. List vs. Linked. List • Implements a list as an array • Implements a list as a doubly -linked list with a header node + Provides random access to the elements - No random access to the elements — needs to traverse the list to get to the i-th element - Inserting and removing elements requires shifting of subsequent elements + Inserting and removing elements is done by rearranging the links — no shifting - Needs to be resized when runs out of space + Nodes are allocated and released as necessary 20
Array. List vs. Linked. List (cont’d) Array. List Linked. List get(i) and set(i, obj) O(1) O(n) add(i, obj) and remove(i) O(n) add(0, obj) O(n) O(1) add(obj) O(1) contains(obj) O(n) 21
Array. List vs. Linked. List (cont’d) for (int i = 0; i < list. size(); i++) { Object x = list. get (i); . . . } Works well for an Array. List O(n) inefficient for a Linked. List O(n 2) Iterator iter = list. iterator ( ); while (iter. has. Next ( )) { Object x = iter. next ( ); . . . } for (Object x : list) {. . . } Work well for both an Array. List and a Linked. List O(n) 22
Stacks • A stack provides temporary storage in the LIFO (Last-In-First-Out) manner. • Stacks are useful for dealing with nested structures and branching processes: Ø Ø Ø pictures within pictures folders within folders methods calling other methods • Controlled by two operations: push and pop. • Implemented as java. util. Stack<E> class 23
Stacks (cont’d) Stack 24
Stack<E> Methods boolean is. Empty ( ) E push (E obj) E pop ( ) E peek ( ) Stack Returns obj; use as void Returns the top element without removing it from the stack 25
Queues • A queue provides temporary storage in the FIFO (First-In-First-Out) manner • Useful for dealing with events that have to be processed in order of their arrival • java. util: Ø Ø Queue interface Linked. List (implements Queue) 26
Queues (cont’d) «interface» Queue Linked. List 27
Queue<E> Methods «interface» Queue Linked. List boolean is. Empty ( ) boolean add (E obj) E remove ( ) E peek ( ) Returns the first element without removing it from the queue 28
Queues (cont’d) Queue<Message> q = new Linked. List<Message> ( ); Methods have been added to Linked. List to implement the Queue interface: add == add. Last remove == remove. First peek == get. First All of the above work in O(1) time 29
Priority Queues • In a priority queue, items are processed NOT in order of arrival, but in order of priority. • java. util: Ø Ø Queue interface Priority. Queue (implements Queue) 30
Priority Queues (cont’d) «interface» Queue Priority. Queue • The same methods as in Queue: is. Empty, add, remove, peek. 31
Priority. Queue<E> Class «interface» Queue Priority. Queue • Works with Comparable objects (or takes a comparator as a parameter). • The smallest item has the highest priority. • Implements a priority queue as a min-heap (Chapter 26). • Both add and remove methods run in O(log n) time; peek runs in O(1) time. 32
Sets • A set is a collection without duplicate values • What is a “duplicate” depends on the implementation • Designed for finding a value quickly • java. util: Ø Ø Ø Set interface Tree. Set Hash. Set 33
Sets (cont’d) «interface» Iterator Methods of Set<E> are the same as methods of Collection<E> «interface» Collection «interface» Set Tree. Set Hash. Set’s semantics are different from Collection (no duplicates), but Set does not add any new methods. 34
Tree. Set<E> «interface» Set Tree. Set Hash. Set • Works with Comparable objects (or takes a comparator as a parameter) • Implements a set as a Binary Search Tree (Chapter 24) • contains, add, and remove methods run in O(log n) time • Iterator returns elements in ascending order 35
«interface» Set Hash. Set<E> Tree. Set Hash. Set • Works with objects for which reasonable hash. Code and equals methods are defined • Implements a set as a hash table (Chapter 25) • contains, add, and remove methods run in O(1) time • Iterator returns elements in no particular order 36
Maps • A map is not a collection; it represents a correspondence between a set of keys and a set of values • Only one value can correspond to a given key; several keys can be mapped onto the same value 37
Maps (cont’d) • java. util: Ø Ø Ø Map interface Tree. Map Hash. Map «interface» Map Tree. Map Hash. Map 38
Map<K, V> Methods «interface» Map Tree. Map Hash. Map boolean is. Empty ( ) int size ( ) V get (K key) V put (K key, V value) V remove (K key) boolean contains. Key (Object key) Set<K> key. Set ( ) Returns the set of all keys 39
Tree. Map<K, V> «interface» Map Tree. Map Hash. Set • Works with Comparable keys (or takes a comparator as a parameter) • Implements the key set as a Binary Search Tree (Chapter 24) • contains. Key, get, and put methods run in O(log n) time 40
Hash. Map<K, V> «interface» Map Tree. Map Hash. Map • Works with keys for which reasonable hash. Code and equals methods are defined • Implements the key set as a hash table (Chapter 25) • contains. Key, get, and put methods run in O(1) time 41
Example: traversing all key-value pairs in a map import java. util. *; . . . Map<Integer, String> presidents = new Tree. Map<Integer, String> ( ); presidents. put (1, “George Washington”); . . . for (Integer key : presidents. key. Set( ) ) { String name = presidents. get (key); System. out. println (key + " : " + name); } 42
Review: • • Why Java collections are called “generic”? Name several methods of Collection. What is an iterator? How can we obtain an iterator for a given collection? • Guess what happens when we call iter. next( ) when there is no next element. 43
Review (cont’d): • • • What are the properties of a list? Name the key methods of the List interface. How is Array. List implemented? How is Linked. List implemented? What is the big-O for the average run time for get(i) in an Array. List and a Linked. List? 44
Review (cont’d): • Name a few methods specific to Linked. List. • Name a few methods specific to List. Iterator. • Can you start iterations at any given position in a list? • How is a set different from a list? • Name a few methods of the Set interface. 45
Review (cont’d): • What is the order of values returned by a Tree. Set iterator? • What is a map? • In a map, can the same key be associated with several different values? 46
Case Study: Stock Exchange • Implements a toy stock exchange • Can be structured as a team development project • Uses Tree. Set, Tree. Map, Hash. Map, Queue, and Priority. Queue classes • A chance to practice structural and object -oriented design 47
Stock Market Basics • Stocks are listed on a stock exchange, such as NYSE (New York Stock Exchange) • A particular stock is identified by its trading symbol (for example, GOOG for Google or MSFT for Microsoft) • Stocks are usually traded in multiples of 100 • Stock prices are in dollars and cents (can include fractions of cents in the real world) • Online brokerage firms allow customers to trade stocks online from their computers 48
Stock Market Terms • Buy order — an order to buy shares of stock • Sell order — an order to sell shares of stock • Limit order — specifies the maximum price for a buy or a minimum price for a sell • Ask — asking price for a sell order • Bid — offer to buy at a certain price • Market order — an order to buy or sell at the market price (the lowest “ask” or the highest “bid, ” respectively) 49
Safe. Trade Program • • Registered users “trade” shares. A user must login first. The program can register a new user. A logged in user can place buy and sell orders and get price quotes for stocks. • Users receive messages when their orders are executed 50
Safe. Trade Program (cont’d) • Runs on a single computer; each active user opens a separate trading window. • Does not keep track of cash or of the number of shares available on each user’s account. 51
Safe. Trade Program (cont’d) 52
Safe. Trade Program Design Data structures used Structural Design Classes and objects OO Design Detailed Design Fields, constructors, and methods 53
Safe. Trade Structural Design Data interface => class Registered traders Map => Tree. Map<String, Trader> Logged-in traders Set => Tree. Set<Trader> Mailbox for each trader Queue => Linked. List<String> Listed stocks Map => Hash. Map<String, Stock> Sell orders for each stock Queue => Priority. Queue<Trade. Order> (with ascending price comparator) Buy orders for each stock Queue => Priority. Queue<Trade. Order> (with descending price comparator) 54
Structural Design — Tradeoffs Registered users: • large number (100, 000 s) • access time is not critical Listed stocks: • relatively small number • fast access time is critical Binary Search Tree (Tree. Map) Hash table (Hash. Map) OK to sacrifice some wasted space for better performance 55
Safe. Trade OO Design 56
Safe. Trade OO Design (cont’d) • Part 1: Trader registration and login A small main class Keeps track of registered and logged in traders 57
Safe. Trade OO Design (cont’d) • Part 2: Stocks and orders Keeps track of listed stocks Represents one stock; keeps track of all orders for the stock Represents one order 58
Safe. Trade Detailed Design • Describes constructors, fields, and methods. • Documentation was generated automatically from javadoc comments in the source code. See JMCh 20Safe. Trade. Docs. zip 59
Safe. Trade Program (cont’d) GUI (supplied by us) Your job (2 -5 team members) 60
Review: • Name a few collections classes used in Safe. Trade. • What is a limit order? • What is a market order? • What data structures are used to hold sell and buy orders for a given stock? Why? • Why is Hash. Map a good choice to represent listed stocks? 61
Review (cont’d): • What data structure would be appropriate for keeping track of stock holdings for each trader? • Explain the role of the Login interface in the Safe. Trade project. 62
27137655705178acd2eba579b5af0f3e.ppt