CS 310: Maps and Sets

Similar documents
CS 310: Maps and Sets and Trees

CS 310: Hash Table Collision Resolution Strategies

CS 310: Hash Table Collision Resolution

CS 310: Hash Table Collision Resolution

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Java Collections. Readings and References. Collections Framework. Java 2 Collections. CSE 403, Spring 2004 Software Engineering

Announcements. Hash Functions. Hash Functions 4/17/18 HASHING

School of Computing and Information Sciences. Course Title: Data Structures Date: 3/30/2010 Course Number: COP 3530 Number of Credits: 3

Class 32: The Java Collections Framework

Announcements. Submit Prelim 2 conflicts by Thursday night A6 is due Nov 7 (tomorrow!)

Java Collections. Readings and References. Collections Framework. Java 2 Collections. References. CSE 403, Winter 2003 Software Engineering

DIT960 Datastrukturer

Topic #9: Collections. Readings and References. Collections. Collection Interface. Java Collections CSE142 A-1

EXAMINATIONS 2016 TRIMESTER 2

Java Collections Framework reloaded

Model Solutions. COMP 103: Mid-term Test. 19th of August, 2016

CS2110: Software Development Methods. Maps and Sets in Java

SUMMARY INTRODUCTION COLLECTIONS FRAMEWORK. Introduction Collections and iterators Linked list Array list Hash set Tree set Maps Collections framework

CS2110: Software Development Methods. Maps and Sets in Java

CS 310: Array-y vs Linky Lists

1. Suppose you are using a HashMap<String,Integer>. What is the runtime of put and get assuming you have a reasonable hash function?

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Collections, Maps and Generics

Programming II (CS300)

Announcements. Container structures so far. IntSet ADT interface. Sets. Today s topic: Hashing (Ch. 10) Next topic: Graphs. Break around 11:45am

Sets and Maps. Part of the Collections Framework

Sets and Maps. Sets Maps The Comparator Interface Sets and Maps in Java Collections API. Review for Exam Reading:

Collections (Java) Collections Framework

Announcements. Today s topic: Hashing (Ch. 10) Next topic: Graphs. Break around 11:45am

CS 2230 CS II: Data structures. Meeting 26: the Set ADT Brandon Myers University of Iowa

27/04/2012. Objectives. Collection. Collections Framework. "Collection" Interface. Collection algorithm. Legacy collection

Model Solutions. COMP 103: Test May, 2013

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

EXAMINATIONS 2012 MID YEAR. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Chapter 5 Java Collection. Wang Yang

MIDTERM EXAM THURSDAY MARCH

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Fall 2017 Mentoring 9: October 23, Min-Heapify This. Level order, bubbling up. Level order, bubbling down. Reverse level order, bubbling up

Today: Java Library Classes for lists. Iterators, ListIterators. CS61B Lecture #7. Last modified: Fri Sep 12 14:41: CS61B: Lecture #7 1

INTRODUCTION TO DATA AND PROCEDURE

CS 314 Exam 2 Spring 2018

CSC 1351: Final. The code compiles, but when it runs it throws a ArrayIndexOutOfBoundsException

USAL1J: Java Collections. S. Rosmorduc

EXAMINATIONS 2015 COMP103 INTRODUCTION TO DATA STRUCTURES AND ALGORITHMS

COMP6700/2140 Abstract Data Types: Queue, Set, Map

COMP 103 : Test. 2019, Jan 9 ** WITH SOLUTIONS **

COURSE 4 PROGRAMMING III OOP. JAVA LANGUAGE

Model Solutions. COMP 103: Test April, 2013

Hash table basics mod 83 ate. ate

Le L c e t c ur u e e 8 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Collections

Points off Total off Net Score. CS 314 Final Exam Spring 2017

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

Hash tables. hashing -- idea collision resolution. hash function Java hashcode() for HashMap and HashSet big-o time bounds applications

EXAMINATIONS 2017 TRIMESTER 2

Lecture 13: AVL Trees and Binary Heaps

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

Interfaces and Collections

Hash table basics. ate à. à à mod à 83

CS11 Java. Winter Lecture 8

The Collections API. Lecture Objectives. The Collections API. Mark Allen Weiss

Taking Stock. IE170: Algorithms in Systems Engineering: Lecture 7. (A subset of) the Collections Interface. The Java Collections Interfaces

Adam Blank Lecture 5 Winter 2019 CS 2. Introduction to Programming Methods

17. Java Collections. Organizing Data. Generic List in Java: java.util.list. Type Parameters ( Parameteric Polymorphism ) Data Structures that we know

COMP 103 : Test. 2018, Sept 12//(Corrected)

Family Name:... Other Names:... ID Number:... Signature... Model Solutions. COMP 103: Test 1. 9th August, 2013

Collections Questions

Topic 10: The Java Collections Framework (and Iterators)

U N I V E R S I T Y O F W E L L I N G T O N EXAMINATIONS 2018 TRIMESTER 2 COMP 103 PRACTICE EXAM

EXAMINATIONS 2012 Trimester 1, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

SOLUTIONS. COMP103 Introduction to Data Structures and Algorithms

Computer Science II (Spring )

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

CS 61B Summer 2005 (Porter) Midterm 2 July 21, SOLUTIONS. Do not open until told to begin

COMP 9024, Assignment 4, 11s2

Today. Book-keeping. Exceptions. Subscribe to sipb-iap-java-students. Collections. Play with problem set 1

Data Structures. Giri Narasimhan Office: ECS 254A Phone: x-3748

Standard ADTs. Lecture 19 CS2110 Summer 2009

APCS Semester #1 Final Exam Practice Problems

Hash table basics mod 83 ate. ate

Domain-Driven Design Activity

Points off Total off Net Score. CS 314 Final Exam Spring 2016

CSC 321: Data Structures. Fall 2016

CSC 321: Data Structures. Fall 2017

CS61BL Summer 2013 Midterm 2

[Ref: Core Java Chp 13, Intro to Java Programming [Liang] Chp 22, Absolute Java Chp 16, docs.oracle.com/javase/tutorial/collections/toc.

Midterm Exam 2 CS 455, Fall 2014

CS 310: ArrayList Implementation

CS 314 Exam 2 Spring

Collections class Comparable and Comparator. Slides by Mark Hancock (adapted from notes by Craig Schock)

Lecture 15 Summary. Collections Framework. Collections class Comparable and Comparator. Iterable, Collections List, Set Map

Data Structures in Java

HEAPS & PRIORITY QUEUES

The class Object. Lecture CS1122 Summer 2008

Lecture 17: Implementing HashTables 10:00 AM, Mar 5, 2018

TECHNICAL WHITEPAPER. Performance Evaluation Java Collections Framework. Performance Evaluation Java Collections. Technical Whitepaper.

Points off Total off Net Score. CS 314 Final Exam Spring Your Name Your UTEID

Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018

Mapping Structures. Chapter An Example: Language Dictionaries

An Interface with Generics

Wentworth Institute of Technology COMP1050 Computer Science II Spring 2017 Derbinsky. Collections & Maps. Lecture 12. Collections & Maps

Transcription:

CS 310: Maps and Sets Chris Kauffman Week 9-1

Logistics Goals Today HW2 Discussion Maps and Sets HW2 Discussion Milestones due Thu 7/6 Discuss AdditiveList Iterator Implementation O(1) Undo/Redo Reading from Weiss Today: Ch 6.7-9 Maps & Sets Upcoming: Trees Ch 18 Trees Ch 19 Binary Search Trees Weiss Ch. 7 Recursion

Operation Complexities (Speed) add(x): put x in the DS removelast(): get rid of "last" item remove(x): take x out of DS contains(x): is x in DS? add(x) removelast() remove(x) contains(x) --------------+----------+--------------+-----------+------------- ArrayList O(1) O(1) O(n) O(n) LinkedList O(1) O(1) O(n) O(n) Hash Table O(1) X O(1) O(1) This table is slightly misleading Careful of semantics of each operation Presence/lack of sorting property Set/Map distinctions What about space complexity of each?

Idea and Implementation List List Idea: Ordered collection, accessible by numeric index: l.get(i) List Idea is formalized in Java s interface List ArrayLists and LinkedLists are both implementation of the List idea with different operational tradeoffs (describe) Could one implement a List with a hash table: HashList? Set and Map Useful ideas: Set of unique items, Mapping of keys to values Can implement set or map with a variety of data structures Arrays, Linked Lists, Hash Tables, Trees

Map and Set Set: HashSet and TreeSet Collection of distinct objects Supports add(x), remove(x), contains(x), sometimes get(x) x is either in the set or not in the set Map: HashMap and TreeMap (key,value) pairs Each key has exactly one value Insert value into a map according to its key Same key maps to same "place" in the data structure Supports put(k,v), get(k), remove(k), contains(k)

Examples of Sets and Maps A data type class Student{ String name; int gnumber; } A set of students Contents {Kyle, 1234} {Stan, 4321} {Eric, 2486} {Kenny, 1313} {Stan, 1357} A map of IDs to students A map of Students to Majors Key Value 1234 -> {Kyle, 1234} 4321 -> {Stan, 4321} 2486 -> {Eric, 2486} 1313 -> {Kenny, 1313} 1357 -> {Stan, 1357} Key {Kyle, 1234} {Stan, 4321} {Eric, 2486} {Kenny, 1313} {Stan, 1357} Value -> World Religions -> Geology -> Nutrition -> Mortuary Sciences -> Genetics/Cloning

Questionable Sets and Maps A set of majors? Contents: World Religions Geology Nutrition Mortuary Sciences Genetics/Cloning A map of IDs to names? Key Value 1234 -> Kyle 4321 -> Stan 2486 -> Eric 1313 -> Kenny 1357 -> Stan A set of names? Contents: Kyle Stan Eric Kenny Stan A map of names to IDs? Key Value Kyle -> 1234 Stan -> 4321 Eric -> 2486 Kenny -> 1313 Stan -> 1357

Array Analogy Arrays and ArrayList are like a Map where Keys are integers: store at array index Values are the objects at those indices A Set of Integers is naturally represented as an array of booleans Represent sets of Integers 0 to 10 Use arrays of size 11 The set {1, 8, 9} is the array boolean set1[] = new boolean[]{ false,true,false,false,false,false, // 1 false,false,true,true,false // 8 9 }; More efficient with BitSet if you re willing...

General Observations Set A set must guarantee uniqueness of elements Typical approach is during add(x), check contains(x) and don t add duplicates but there are other approaches Efficient implementation of contains(x) and get(x) becomes important for sets Map The collection so keys is a set - each key must be unique contains(k)/get(k) important - make them efficient Collection of values is not unique Usually not efficient to look up whether a given value is present Collection of (key,value) pairs is unique due to keys being unique

General Implementations How would you implement a Set<T>? Using an ArrayList? Using an LinkedList? Using a Hash Table? How would you implement a Map<K,V>? Using an ArrayList? Using an LinkedList? Using a Hash Table?

General Solutions Set from a Array or Linked List Guarantee items in list are unique by searching Could sort array for efficient lookup via binary search Still looking at O(N) operations somewhere Set from Hash Table Good fit: O(1) lookup via hash codes Keep load low and your in good shape Map from Array or Linked List Keep track of Pairs of (Key,Value) Lookup is based on only Key Can sort based on Key part only O(N) operations somewhere Map based on Hash Table Keep track of pairs of (Key,Value) Hash only the Key part O(1) lookups if load is low

Have Set, Build Map Q: If I have Set, how would I build Map? Given: SimpleSet Build: SimpleMap Collection of distinct objects Uniqueness determined by equals() method Operations add(x), get(x), remove(x), contains(x) SimpleSet implementation may be based on arrays, hash tables, trees, linked lists... you don t know Set of (key,value) pairs Compare pairs only on whether their key is equal (a,x) == (a,x) (a,x) == (a,y) (a,x)!= (b,y) (a,x)!= (b,x) Use the set to ensure no redundant keys enter Implement put(k,v), get(k), remove(k), contains(k)

Trick 1: Use an internal class public class MapFromSet<K, V>{ // Trick: Use a nested class // Class to carry around (key,val) pairs public static class KeyVal<K, V>{ public K key; public V value; public KeyVal(K key, V value){ this.key = key; this.value = value; } // Required for any set to work // Compare only based on key public boolean equals(object o); // Required for HashSet to work right public int hashcode(); // Required for TreeSet to work public int compareto(keyval<k,v> kv); }

Trick 2: Use a set of the key/val pairs Prototypes public interface SimpleSet<T> { boolean contains(t x); boolean add(t x); boolean remove(t x); T get(t x); } public class MapFromSet<K, V>{ // Trick 1: Use internal key/val class public static class KeyVal<K, V>{...} } // Trick 2: Given a working Set class: use it! private SimpleSet< KeyVal<K,V> > theset; // Implement these using theset public MapFromSet(); public void put(k key, V value); public void remove(k key); public boolean contains(k key); public V get(k key); Exercise Implement the put(), remove(), contains(), get() methods

The other Direction: Build a Set from a Map Given a SimpleMap (key,value) pairs Each key is unique Insert value into a map according to its key Same key maps to same "place" in the data structure Supports put(k,v), remove(k), contains(k) Build a SimpleSet Use an internal SimpleMap Implement SimpleSet methods void add(t x) void remove(t x) T get(t x) boolean contains(t x) A Great Exam Question Tests your use of generics Illustrates abstraction skills Show you re a proper software engineer

Java Does it In Java: Map Set java.util.treemap is a red-black tree java.util.treeset uses a TreeMap java.util.hashmap is a separate chained hash table java.util.hashset uses a HashMap In Weiss: Set Map weiss.util.treeset is an AA-tree (another balanced tree) weiss.util.treemap uses TreeSet weiss.util.hashmap uses HashSet Lesson Re-use when it makes sense Think hard about when it makes sense to re-use