Some Other Collections: Bags, Sets, Queues and Maps COMP 103 2014-T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.

Slides:



Advertisements
Similar presentations
Why not just use Arrays? Java ArrayLists.
Advertisements

Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Stacks, Queues, and Linked Lists
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
COMP 103 Linked Stack and Linked Queue.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
TCSS 342, Winter 2005 Lecture Notes
Stacks, Queues, and Deques
Stacks, Queues, and Deques
Building Java Programs
Java Collections. Collections, Iterators, Algorithms CollectionsIteratorsAlgorithms.
CSE373 Optional Section Java Collections 11/12/2013 Luyi Lu.
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.
Java Collections Framework A presentation by Eric Fabricant.
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.
COMP T2 Lecture 5 School of Engineering and Computer Science, Victoria University of Wellington Thomas Kuehne Maps, Stacks  Thomas Kuehne, Marcus.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Data Structures and Abstract Data Types "Get your data structures correct first, and the rest of the program will write itself." - David Jones.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
JAVA COLLECTIONS LIBRARY School of Engineering and Computer Science, Victoria University of Wellington COMP T2, Lecture 2 Marcus Frean.
Information and Computer Sciences University of Hawaii, Manoa
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.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington2012 More Collections: Queues,
Chapter 18 Java Collections Framework
COMP 103 Linked Lists. 2 RECAP-TODAY RECAP  Linked Structures: LinkedNode  Iterating and printing Linked Nodes  Inserting and removing Linked Nodes.
Data structures Abstract data types Java classes for Data structures and ADTs.
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.
Interfaces, Classes, Collections School of Engineering and Computer Science, Victoria University of Wellington COMP T2 Lecture 3 Thomas Kuehne.
1 Stacks (Continued) and Queues Array Stack Implementation Linked Stack Implementation The java.util.Stack class Queue Abstract Data Type (ADT) Queue ADT.
Week 2 - Friday.  What did we talk about last time?  Computing Big Oh.
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 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.
Collections Dwight Deugo Nesa Matic
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.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
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.
Linked Data Structures
Using the Java Collection Libraries COMP 103 # T2
Building Java Programs
Collections COMP 103 #3 2008T2.
Unit 1 Hadoop and big data
Some Collections: BAGS, SETS, and STACKS
JAVA COLLECTIONS LIBRARY
JAVA COLLECTIONS LIBRARY
COMP 103 Maps, Stacks Thomas Kuehne 2016-T2 Lecture 5
Building Java Programs
Week 2: 10/1-10/5 Monday Tuesday Wednesday Thursday Friday
Building Java Programs
Building Java Programs
Generics, Stack, Queue Based on slides by Alyssa Harding
CS 240 – Advanced Programming Concepts
Presentation transcript:

Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington Marcus Frean

RECAP  We met the almighty ArrayList and saw it was an implementation of the abstract data type List TODAY  A note on “Autoboxing”  Some other collection types: Bags, Sets, Queues, Maps Announcements:  Assignment#1 is out today (pick it up here at end of lecture)  Tutorials started today (9am!)  class reps: can I have your forms / details thanks 2 RECAP and TODAY

3 What can you put in a Collection ?  The type parameter of a collection can be any object type.  private List creatures = new ArrayList ();  public void processStrings(Set strings){…  Set > allJobs = new HashSet > ();  What about collections of numbers, or booleans, or chars…  private List myNums = new ArrayList ();  public int computeScore(List answers){….  Must use “wrapper classes”:  Integer, Boolean, Double, Char, etc  private List myNums = new ArrayList ();  public int computeScore (List answers) {…. Problem: these are “primitive types”, not Objects

4 Collection of Primitive Types  You could “wrap” a primitive type inside a wrapper object: List myNums = new ArrayList (); Integer num = new Integer(15); myNums.add(num);  And could write methods that “unwrap” again: int sum = 0; for (Integer num : myNums){ int n = num.intValue(); sum = sum + n; }  But this is just a pain!

 Good news: Java will do it automatically for you private List myNumbers = new ArrayList (); myNumbers.add(15); int sum = 0; for (Integer num : myNumbers) { sum = sum + num; } Or for (int num : myNumbers){ sum = sum + num; }  Java Auto-boxes a primitive type if a wrapper type is expected  and Auto-unboxes a wrapper type when primitive type expected. Auto-boxing 5

Sets  Set is a collection with:  no structure or order maintained  no access constraints (access any item any time)  Only property is that duplicates are excluded  Operations: (same as Bag, but different behaviour)  add(value) → true iff value was added (eg, not duplicate)  remove(value) → true iff value removed (was in set)  contains(value) → true iff value is in the set  findElement(value) → matching item, iff in value in the set ……  Sets are as common as Lists 6

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)) UI.println(“Yes, ”+wd+“ is in the book”); else UI.println(“No, ”+wd+“ is not in the book”); } make an empty set add words to it check if a particular word is in the set 7

Interfaces:  Collection = Bag (most general)  List = ordered collection  Set = unordered, no duplicates  [Stack (not an interface!) ordered collection, limited access (add/remove at one end) ]  Map = key-value pairs (or mapping)  Queue ordered collection, limited access (add at end, remove from front) Collections library Classes:  List classes: ArrayList, LinkedList, Vector  Set classes: HashSet, TreeSet, EnumSet, LinkedHashSet,…  Stack classes: Stack  Map classes: EnumMap, HashMap, TreeMap, LinkedHashMap, WeakHashMap, …  … 8

Bags  A Bag is a collection with  no structure or order maintained  no access constraints (access any item any time)  duplicates allowed  examples ? A collection of current logged-on users. Bingo cards. The books in a book collection …  But not all that common! Typically we don’t really have duplicate items.  There are no standard implementations of Bag!! 9

Bags Java could have a Bag interface, like this: public interface Bag extends Collection {... But we might as well use the “Collection” interface itself. So if java had an implementation that used an array, then public class ArrayBag implements Collection {...  Minimal Operations:  add(value) → returns true iff a collection was changed  remove(value) → returns true iff a collection was changed  contains(value) → returns true iff value is in bag, uses equal to test.  findElement(value) → returns a matching item, iff in bag  Plus.... size(), isEmpty(), iterator(), clear(), addAll(collection), … 10

Queues  Queues embody the principle of “First In, First Out” (FIFO)  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 11

Queues Some uses:  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 Artificial Intelligence, Computer Games Java provides :  a Queue interface  several classes (ie. implementations) : LinkedList, PriorityQueue,... 12

Queue Operations  offer(value) ⇒ boolean  add a value to the queue  (sometimes called “enqueue”, like “push” )  poll() ⇒ value  remove and return value at front/head of queue or null if the queue is empty  (sometimes called “dequeue”, like “pop”)  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.  A question: Why use Queue instead of List ?? 13

Maps 14 Key Value Not this kind of MAP Something that MAPs a key to a value NameAge Bob25 Rita34 Sam15 Adam 6 : : :

Maps  Collection of data, but not of single values:  Map = a set of pairs of keys and values  Constrained access: get values via keys.  No duplicate keys  Lots of implementations, most common is HashMap. “Sharon” ⇒ 228 “Marcus” ⇒ 227 “Becky” ⇒ 353 “Pondy” ⇒ 336 get (“Becky”) put (“Sharon”, 336) 15 remove(“Marcus”) put (“Pondy”, 336)

Maps  When declaring and constructing, must specify two types:  Type of the key, and type of the value private Map phoneBook; : phoneBook = new HashMap ();  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() 16