Download presentation
Presentation is loading. Please wait.
Published byCaitlin Warren Modified over 9 years ago
1
Some Other Collections: Bags, Sets, Queues and Maps COMP 103 2014-T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington Marcus Frean
2
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
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
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!
5
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
6
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
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
Maps 14 Key Value Not this kind of MAP Something that MAPs a key to a value NameAge Bob25 Rita34 Sam15 Adam 6 : : :
15
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)
16
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.