1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.

Slides:



Advertisements
Similar presentations
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.
Advertisements

June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 7 Object Oriented Programming in Java Advanced Topics Collection.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
15-Jun-15 Lists in Java Part of the Collections Framework.
Algorithm Programming Containers in Java Bar-Ilan University תשס " ו by Moshe Fresko.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 17 Advanced Java Concepts Data Structure Support.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
Lists in Java Part of the Collections Framework. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
12-Jul-15 Lists in Java Part of the Collections Framework.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 11: Java Collections Framework.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
CSE 143 Lecture 15 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Java's Collection Framework
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
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.
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
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.
Recitation 1 CS0445 Data Structures Mehmud Abliz.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
(c) University of Washington14-1 CSC 143 Java Collections.
1 Sets and Maps Starring: keySet Co-Starring: Collections.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Building Java Programs Chapter 11 Lecture 11-1: Sets and Maps reading:
1 Building Java Programs Java Collections Framework.
תוכנה 1 תרגול 8 – מבני נתונים גנריים. 2 Java Collections Framework Collection: a group of elements Interface Based Design: Java Collections Framework.
Data structures Abstract data types Java classes for Data structures and ADTs.
Collections in Java. 2 Collections Hierarchy > ArrayListVector Stack LinkedList > Arrays Collections.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
The Java Collections Framework Based on
CSC 142 P 1 CSC 142 Collections [Reading: Chapter 10]
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Java 2 Collections Bartosz Walter Software Engineering II.
1 Collection, Iterable, and Iterator Interfaces The Collection Interface and its Hierarchy The Iterable and Iterator Interfaces For-each Loops with Iterable.
1 Collections Framework A collections framework is a unified architecture for representing and manipulating collections. All collections frameworks contain:
SETS AND MAPS Collections of Data. Advanced Data Structures Often referred to as the Java Collections Framework…. Set and map data types Hash tables Binary.
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Maps Nick Mouriski.
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.
CMSC 202 Containers and Iterators. Container Definition A “container” is a data structure whose purpose is to hold objects. Most languages support several.
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
4-Mar-16 Introduction to Collections. Revision questions True false questions 0 for False 1 for True Please do not answer anything other than the above.
Collections Dwight Deugo Nesa Matic
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
CSE 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
Java Collections CHAPTER 3-February-2003
TCSS 342, Winter 2006 Lecture Notes
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
TCSS 342, Winter 2006 Lecture Notes
Introduction to Collections
Part of the Collections Framework
TCSS 342, Winter 2005 Lecture Notes
CS2110: Software Development Methods
Introduction to Collections
Introduction to Collections
slides created by Marty Stepp
Hashing in java.util
Part of the Collections Framework
Presentation transcript:

1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets

2 Lists, revisited Lists are slow for searching indexOf, contains are slow (O(n)) must potentially look at each element of list public int indexOf(Object o) { for (int i = 0; i < size(); i++) if (get(i).equals(o)) return i; return -1; }

3 A new collection type: Set set: an unordered collection with no duplicates main purpose of a set is to test objects for membership operations are exactly those for Collection interface java.util.Set has the following methods: int size(); boolean isEmpty(); boolean contains(Object e); boolean add(Object e); boolean remove(Object e); Iterator iterator(); boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); Object[] toArray(); Object[] toArray(Object[] a);

4 Set implementations in Java Set is an interface; you can't say new Set() There are two implementations: java.util.HashSet is best for most purposes we won't use the other one: TreeSet Java's set implementations have been optimized so that it is very fast to search for elements in them contains method runs in constant time! (How?!) Preferred: Set s = new HashSet(); Not: HashSet s = new HashSet();

5 Limitations of Sets Why are these methods missing from Set ? get(int index) add(int index, Object o) remove(int index) How do we access the elements of the set? How do we get a particular element out of the set, such as element 0 or element 7? What happens when we print a Set ? Why does it print what it does?

6 Iterators for Sets A set has a method iterator to create an iterator over the elements in the set The iterator has the usual methods: boolean hasNext() Object next() void remove()

7 Typical set operations Sometimes it is useful to compare sets: subset: S1 is a subset of S2 if S2 contains every element from S1. Many times it is useful to combine sets in the following ways: union: S1 union S2 contains all elements that are in S1 or S2. intersection: S1 intersect S2 contains only the elements that are in both S1 and S2. difference: S1 difference S2 contains the elements that are in S1 that are not in S2. How could we implement these operations using the methods in Java's Set interface?

8 How does a HashSet work? every object has a reasonably-unique associated number called a hash code public int hashCode() in class Object HashSet stores its elements in an array a such that a given element o is stored at index o.hashCode() % array.length any element in the set must be placed in one exact index of the array searching for this element later, we just have to check that one place to see if it's there (O(1)) "Tom Katz".hashCode() % 10 == 6 "Sarah Jones".hashCode() % 10 == 8 "Tony Balognie".hashCode() % 10 == 9 you don't need to understand this...

9 Membership testing in HashSets When testing whether a HashSet contains a given object: Java computes the hashCode for the given object looks in that index of the HashSet 's internal array Java compares the given object with the object in the HashSet 's array using equals ; if they are equal, returns true Hence, an object will be considered to be in the set only if both: It has the same hash code as an element in the set, and The equals comparison returns true an object that is put into a HashSet works best if it has a public int hashCode() method defined String, Integer, Double, etc. have this already

10 Set practice problems Modify our Sieve of Eratosthenes to return a Set of primes, instead of just printing them. Given a List of elements or string of many words, determine if it contains any duplicates, using a Set. (You can use a Scanner to break up a String by words.)

11 Mapping between sets sometimes we want to create a mapping between elements of one set and another set example: map people to their phone numbers "Marty Stepp"-->" " "Jenny"-->" " How would we do this with a list (or list(s))? A list doesn't map people to phone numbers; it maps int s from 0.. size - 1 to objects Could we map some int to a person's name, and the same int to the person's phone number? How would we find a phone number, given the person's name? Is this a good solution?

12 A new collection: Map map: an unordered collection that associates a collection of element values with a set of keys so that elements they can be found very quickly (O(1)!) Each key can appear at most once (no duplicate keys) A key maps to at most one value the main operations: put(key, value) "Map this key to that value." get(key) "What value, if any, does this key map to?" maps are also called: hashes or hash tables dictionaries associative arrays

13 Java's Map interface public interface Map { Object put(Object key, Object value); Object get(Object key); Object remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); void putAll(Map map); void clear(); Set keySet(); Collection values(); } Basic ops Bulk ops Collection views

14 Map implementations in Java Map is an interface; you can't say new Map() There are two implementations: java.util.HashMap is best for most purposes we won't use the other one: TreeMap Preferred: Map m = new HashMap(); Not: HashMap m = new HashMap();

15 HashMap example HashMap grades = new HashMap(); grades.put("Martin", "A"); grades.put("Nelson", "F"); grades.put("Milhouse", "B"); // What grade did they get? System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); grades.put("Nelson", "W"); grades.remove("Martin"); System.out.println( grades.get("Nelson")); System.out.println( grades.get("Martin")); HashMap HashMap grades HashMapEntry "Martin""A" HashMapEntry "Nelson""F" HashMapEntry "Milhouse""B"

16 Map example public class Birthday { public static void main(String[] args){ Map m = new HashMap(); m.put("Newton", new Integer(1642)); m.put("Darwin", new Integer(1809)); System.out.println(m); } Output: {Darwin=1809, Newton=1642}

17 Some Map methods in detail public Object get(Object key) returns the value at the specified key, or null if the key is not in the map (constant time) public boolean containsKey(Object key) returns true if the map contains a mapping for the specified key (constant time) public boolean containsValue(Object val) returns true if the map contains the specified object as a value this method is not constant-time O(1)... why not?

18 Collection views A map itself is not regarded as a collection Map does not implement Collection interface although, in theory, it could be seen as a collection of pairs, or a relation in discrete math terminology Instead collection views of a map may be obtained Set of its keys Collection of its values (not a set... why?)

19 Iterators and Maps Map interface has no iterator method; you can ’ t get an Iterator directly must first call either keySet() returns a Set of all the keys in this Map values() returns a Collection of all the values in this Map then call iterator() on the key set or values Examples: Iterator keyItr = grades.keySet().iterator(); Iterator elementItr = grades.values().iterator(); If you really want the keys or element values in a more familiar collection such as an ArrayList, use the ArrayList constructor that takes a Collection as its argument ArrayList elements = new ArrayList(grades.values());

20 Examining all elements Usually iterate by getting the set of keys, and iterating over that Set keys = m.keySet(); Iterator itr = keys.iterator(); while (itr.hasNext()) { Object key = itr.next(); System.out.println(key + "=>" + m.get(key)); } Output: Darwin => 1809 Newton => 1642

21 Map practice problems Write code to invert a Map ; that is, to make the values the keys and make the keys the values. Map byName = new HashMap(); byName.put("Darwin", " "); byName.put("Newton", " "); Map byPhone = new HashMap(); //... your code here! System.out.println(byPhone); Output: { =Darwin, =Newton} Write a program to count words in a text file, using a hash map to store the number of occurrences of each word.

22 Java Collections Framework

23 Compound collections Collections can be nested to represent more complex data example: A person can have one or many phone numbers want to be able to quickly find all of a person's phone numbers, given their name implement this example as a HashMap of Lists keys are Strings (names) values are Lists (e.g ArrayList) of Strings, where each String is one phone number

24 Compound collection code 1 // map names to list of phone numbers Map m = new HashMap(); m.put("Marty", new ArrayList());... ArrayList list = m.get("Marty"); list.add(" ");... list = m.get("Marty"); list.add(" "); System.out.println(list); [ , ]

25 Compound collection code 2 // map names to set of friends Map m = new HashMap(); m.put("Marty", new HashSet());... Set set = m.get("Marty"); set.add("James");... set = m.get("Marty"); set.add("Mike"); System.out.println(set); if (set.contains("James")) System.out.println("James is my friend"); {Mike, James} James is my friend

26 References Koffman/Wolfgang Ch. 9, pp The Java Tutorial: Collections. collections/index.html JavaCaps Online Tutorial: java.util package.