some other collections: bags, sets, queues and maps comp 103 2014-t2 lecture 4 school of engineering...

16
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

Upload: caitlin-warren

Post on 02-Jan-2016

214 views

Category:

Documents


1 download

TRANSCRIPT

Page 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

Some Other Collections:Bags, Sets, Queues and Maps

CO

MP 1

03

2014-T2 Lecture 4

School of Engineering and Computer Science, Victoria University of Wellington

Marcus Frean

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

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

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

3What can you put in a Collection? The type parameter of a collection can be any object type. private List <Creature> creatures = new ArrayList <Creature>(); public void processStrings(Set <String> strings){… Set <List <Task>> allJobs = new HashSet <List<Task>> ();

What about collections of numbers, or booleans, or chars… private List <int> myNums = new ArrayList <int> (); public int computeScore(List<boolean> answers){….

Must use “wrapper classes”: Integer, Boolean, Double, Char, etc private List <Integer> myNums = new ArrayList <Integer> (); public int computeScore (List<Boolean> answers) {….

Problem: these are “primitive types”,

not Objects

Problem: these are “primitive types”,

not Objects

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

4Collection of Primitive Types

You could “wrap” a primitive type inside a wrapper object:

List <Integer> myNums = new ArrayList <Integer> ();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!

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

Good news: Java will do it automatically for you

private List <Integer> myNumbers = new ArrayList <Integer>();

myNumbers.add(15); int sum = 0;for (Integer num : myNumbers) {

sum = sum + num;}

Orfor (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-boxing5

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

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

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

Using Sets Checking vocabulary of children’s books:

private Set <String> words = new HashSet <String> ();

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

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

Interfaces: Collection <E >

= Bag (most general) List <E >

= ordered collection Set <E >

= unordered, no duplicates

[Stack <E > (not an interface!)ordered collection, limited access(add/remove at one end) ]

Map <K, V >

= key-value pairs (or mapping)

Queue <E >ordered collection, limited access(add at end, remove from front)

Collections libraryClasses:

List classes: ArrayList, LinkedList, Vector

Set classes:HashSet, TreeSet, EnumSet, LinkedHashSet,…

Stack classes:Stack

Map classes:EnumMap, HashMap, TreeMap, LinkedHashMap, WeakHashMap, …

8

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

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

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

Bags

Java could have a Bag interface, like this:public interface Bag <E> extends Collection <E> {...

But we might as well use the “Collection” interface itself.So if java had an implementation that used an array, then

public class ArrayBag<E> implements Collection<E> {...

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

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

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

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

QueuesSome 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

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

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

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

Maps14

Key Value

Not this kind of MAPSomething that MAPs a key to a value

Name AgeBob 25Rita 34Sam 15Adam 6 : : : :

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

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)

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

Maps When declaring and constructing, must specify two types:

Type of the key, and type of the valueprivate Map <String, Integer> phoneBook;

:phoneBook = new HashMap <String, Integer> ();

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