Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,

Slides:



Advertisements
Similar presentations
Stacks, Queues, and Linked Lists
Advertisements

Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Queues Ellen Walker CPSC 201 Data Structures Hiram College.
COMP 103 Linked Stack and Linked Queue.
Unit 11 1 Unit 11: Data Structures H We explore some simple techniques for organizing and managing information H This unit focuses on: Abstract Data Types.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Building Java Programs
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
Java's Collection Framework
COMP 103 Iterators and Iterable. RECAP  Maps and Queues TODAY  Queue Methods  Iterator and Iterable 2 RECAP-TODAY.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
CSE 373 Data Structures and Algorithms Lecture 2: Queues.
Sets and Maps Part of the Collections Framework. The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks  Thomas Kuehne, Marcus.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArraySet and Binary Search.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Priority Queues Dr. David Matuszek
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Stacks and Queues. 2 3 Runtime Efficiency efficiency: measure of computing resources used by code. can be relative to speed (time), memory (space), etc.
2014-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
2013-T2 Lecture 18 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington 2D arrays COMP 102 # T1.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Thomas Kuehne.
CSE 373: Data Structures and Algorithms Lecture 2: Queues.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington ArrayLists: varying size arrays.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Marcus Frean.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
1 Maps, Stacks and Queues Maps Reading:  2 nd Ed: 20.4, 21.2, 21.7  3 rd Ed: 15.4, 16.2, 16.7 Additional references: Online Java Tutorial at
2015-T2 Lecture 19 School of Engineering and Computer Science, Victoria University of Wellington  Marcus Frean, Lindsay Groves, Peter Andreae, and John.
© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
COMP 103 Maps and Queues. RECAP  Iterators (for-each loop)  Bag, Sets, and Stacks - a class, not interface TODAY  Maps and Queues 2 RECAP-TODAY QUICK.
Java Collections Framework The client view. The Big Picture.
Stacks and Queues. 2 Abstract Data Types (ADTs) abstract data type (ADT): A specification of a collection of data and the operations that can be performed.
Using the Java Collection Libraries COMP 103 # T2
Building Java Programs
Collections COMP 103 #3 2008T2.
QueueStack CS1020.
Some Collections: BAGS, SETS, and STACKS
Stacks and Queues.
JAVA COLLECTIONS LIBRARY
JAVA COLLECTIONS LIBRARY
CSE 373: Data Structures and Algorithms
Stacks and Queues.
COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5
CS240: Advanced Programming Concepts
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Building Java Programs
Queues, Deques and Priority Queues
Queues, Deques and Priority Queues
Stacks and Queues.
Part of the Collections Framework
Java Collections Framework
Stacks and Queues CLRS, Section 10.1.
Stacks and Queues.
Presentation transcript:

Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues, Maps COMP 103 # T2

© Peter Andreae COMP :2 Menu More Collections Queues and applications Maps and applications Sets Notices: Tutorials this week Help desk and online help Assignments

© Peter Andreae COMP :3 Queues Queues are like lists, but constrained: Collection of values with an order Constrained access: Only remove from the front Two varieties: Ordinary queues: only add at the back Priority queues: add with a given priority

© Peter Andreae COMP :4 Queues Used for Operating Systems, Network Applications, multi-user systems Handling requests/events/jobs that must be done in order (often called a “buffer” in this context) Simulation programs Representing queues in the real world (traffic, customers, deliveries, ….) Managing the events that must happen in the future Search Algorithms Computer Games Artificial Intelligence Java provides a Queue interface several classes: LinkedList, PriorityQueue, ….

© Peter Andreae COMP :5 Queue Operations offer(value) ⇒ boolean (sometimes called “enqueue” ) add a value to the queue poll() ⇒ value (sometimes called “dequeue” ) remove and return value at front/head of queue or null if the queue is empty peek() ⇒ value return value at head of queue, or null if queue is empty (doesn’t remove from queue) remove() and element() like poll() and peek(), but throw exception if queue is empty. and all the Collection operations Why use Queue instead of List??

© Peter Andreae COMP :6 A Queue Example. Simulation of a bank with two teller queues: want to see how it will cope with various client loads: how big might the queues get? assume that each client will go to the shortest queue What do we care about? How often a new client turns up. Probability of arriving How long a client will take at the teller Represent client by number of timesteps they will take.

© Peter Andreae COMP :7 A Queue Example. public void simulate(int serveTime, double probArrival){ int t1 = 0; // how many more time steps will the teller be busy int t2 = 0; Queue q1 = new LinkedList (); Queue q2 = new LinkedList (); for (int time =0; time< MaxTime; time++){ if ( Math.random()< probArrival) { int client = (int) (Math.random()*serveTime); if ( q1.size()<q2.size() ) q1.offer(client); else q2.offer(client); } if ( t1==0 && !q1.isEmpty() ) t1 = q1.poll(); if ( t2==0 && !q2.isEmpty() ) t2 = q2.poll(); if (t1 > 0) t1-- ; if (t2 > 0) t2-- ; UI.printf("queues: %d %d /n", q1.size(), q2.size()); }}

© Peter Andreae COMP :8 Collection of data, but not of single values: Map = set of pairs of keys to values Constrained access: get values via keys. No duplicate keys Lots of implementations, most common is HashMap. Maps “Sharon” ⇒ 5978 “David” ⇒ 5656 “Marcus” ⇒ 5672 “Will” ⇒ 5670 “Pondy” ⇒ 5834 get(“Pondy”) put(“Pondy”, 1212) put(“James”, 5134)

© Peter Andreae COMP :9 When declaring and constructing, must specify two types: Type of the key, and type of the value private Map phoneBook; : phoneBook = new HashMap (); Central operations: get(key), → returns value associated with key (or null) put(key, value),→ sets the value associated with key (and returns the old value, if any) remove(key), → removes the key and associated value (and returns the old value, if any) containsKey(key), → boolean size() Maps

© Peter Andreae COMP :10 Example of using Map /** Construct histogram of counts of all temperatures in a file */ public Map countTemps(Scanner sc){ // construct new map // for each temperature in file // if temperture is in the map, increment its count // else, put it in map with a count of 1 // return map } /** Find temperture in histogram with highest count */ public Double findMostFrequentTemp(Map counts){ // for each temperature in map // if has higher count than current most frequent, record it // return most frequent temp } UI.println(findMostFrequentTemp(countTemps(tempFileScanner)));

© Peter Andreae COMP :11 Example of using Map /** Construct histogram of counts of all temperatures in a file */ public Map countTemps(Scanner scan){ Map counts = new HashMap (); while (scan.hasNext()){ double temp = scan.nextDouble(); if ( counts.containsKey(temp) ) counts.put(temp, counts.get(temp)+1); else counts.put(temp, 1); } return counts; } /** Find most frequent temperature */ public Double findMostFrequentTemp(Map counts){ // for each temperature in map // if has higher count than current most frequent, record it // return most frequent temp }

© Peter Andreae COMP :12 Iterating through a Map How do you iterate through a Map? (eg, to print it out) A Map isn’t just a collection of items! ⇒ could iterate through the collection of keys ⇒ could iterate through the collection of values ⇒ could iterate through the collection of pairs Java Map allows all three! keySet()→ Set of all keys for (String name : phonebook.keySet()){…. values()→ Collection of all values for (Integer num : phonebook.values()){…. entrySet()→ Set of all Map.Entry’s for (Map.Entry entry : phonebook.entrySet()){…. … entry.getKey() … … entry.getValue()…

© Peter Andreae COMP :13 Iterating through Map: keySet /** Find most frequent temperature */ public Double findMostFrequentTemp(Map counts){ double mfTemp = Double.NaN; int maxCount = -1; for (Double temp : counts.keySet() ){ int count = counts.get(temp); if (count > maxCount){ maxCount = count; mfTemp = temp; } return mfTemp; }

© Peter Andreae COMP :14 Iterating through Map: entrySet public Double findMostFrequentTemp(Map counts){ double mfTemp = Double.NaN; int maxCount = -1; for (Map.Entry entry : counts.entrySet() ){ if (entry.getValue() > maxCount){ maxCount = entry.getValue(); mfTemp = entry.getKey(); } return mfTemp; } “public” ⇒ 1 “Map” ⇒ 2 “String” ⇒ 5 “counts” ⇒ 2 “findMaxCount” ⇒ 1 Map.Entry - getKey() - getValue()

© Peter Andreae COMP :15 Another example of Map private Map movieCast = new Ha; // character → actor : public void lookup(){ String name = UI.askString(“Character to look up"); if (movieCast.containsKey(name)) UI.println(name +" : "+movieCast.get(name)); else UI.println("No entry for "+ name); } public void update(){ String name = askName(“Character to update"); String actor =askName(“Actor who played "+name); String old = movieCast.put(name, actor); if (old==null) UI.println(" added "+name +" played by " + actor); else UI.println(" replaced "+old+" by "+actor+ " for " + name)); }

© Peter Andreae COMP :16 Sets Set is a collection with: no structure or order maintained no access constraints (access any item any time) Only constraint is that duplicates are excluded Operations: add(value) → true iff collection changed (ie, not duplicate) remove(value) → returns true iff a collection was changed contains(value)→ returns true iff value is in bag uses equal to test. Plus size(), isEmpty(), iterator(), clear(), addAll(collection), removeAll(collection)… Standard implementations: HashSet, TreeSet,

© Peter Andreae COMP :17 Using Sets Checking vocabulary of children’s books: private Set words = new HashSet (); public void readBook(Scanner sc){ while (sc.hasNext ()) words.add(sc.next()); } public void checkWord(String wd){ if (words.contains(wd)) System.out.println(“Yes, ”+wd+“ is in current book”); else System.out.println(“No, ”+wd+“ is not in current book”); } public void printVocab(){ for (String word : words) System.out.println(wd); }