TCSS 342, Winter 2006 Lecture Notes

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

CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
15-Jun-15 Lists in Java Part of the Collections Framework.
What Is a Collection?  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 8.
24-Jun-15 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Data Structures & Java Collections Fawzi Emad Chau-Wen Tseng 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.
1 ADTs, Collection, Iterable/Iterator Interfaces Collections and the Java Collections API The Collection Interface and its Hierarchy The Iterable and Iterator.
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.
Collections in Java. Kinds of Collections Collection --a group of objects, called elements –Set-- An unordered collection with no duplicates SortedSet.
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
1 Building Java Programs Java Collections Framework.
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
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
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.
CS Ananda Gunawardena.  A collection (sometimes called a container) is simply an object that groups multiple elements into a single unit.  Collections.
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.
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 143 Lecture 11: Sets and Maps reading:
3-1 Java's Collection Framework Another use of polymorphism and interfaces Rick Mercer.
CS2005 Week 7 Lectures Set Abstract Data Type.
Java Collections CHAPTER 3-February-2003
Slides by Donald W. Smith
Java Collections OOP tirgul No
Using the Java Collection Libraries COMP 103 # T2
CSc 110, Autumn 2016 Lecture 26: Sets and Dictionaries
Sets Set is an unordered list of items
Wednesday Notecards. Wednesday Notecards Wednesday Notecards.
Programming & Data Structures
JAVA COLLECTIONS LIBRARY
CSc 110, Spring 2018 Lecture 32: Sets and Dictionaries
Road Map CS Concepts Data Structures Java Language Java Collections
Introduction to Collections
Introduction to Collections
TCSS 143, Autumn 2004 Lecture Notes
JAVA Collections Framework Set Interfaces & Implementations
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Java Collections Framework
Maps "He's off the map!" -Stan (Mark Ruffalo) Eternal Sunshine of the Spotless Mind.
EE 422C Sets.
Sets, Maps and Hash Tables
TCSS 342, Winter 2005 Lecture Notes
"He's off the map!" - Eternal Sunshine of the Spotless Mind
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
CS2110: Software Development Methods
Introduction to Collections
Collections Framework
Introduction to Collections
Containers and Iterators
slides created by Marty Stepp
Part of the Collections Framework
CSE 373 Set implementation; intro to hashing
Presentation transcript:

TCSS 342, Winter 2006 Lecture Notes Java’s Set ADT Java’s Map ADT Sample Word Finding/Counting application version 1.0

Objectives Learn more about Java’s Collection API Set Map Learn how Set and Map are used Discuss the basics of how they are implemented

Application: words in a book Write an application that reads in the text of a book (say, Moby Dick) and then lets the user type words, and tells whether those words are contained in Moby Dick or not. How would we implement this with a List? Would this be a good or bad implementation? Does the ordering of the elements in the List affect the algorithm? Could we use this information to our advantage? Alternative: Use ArraySet implementing SetADT

Java’s Set ADT set: an unordered collection with no duplicates main purpose of a set is to test objects for membership in the set (contains) Java has an interface java.util.Set to represent this kind of collection Set is an interface; you can't say new Set() There are two Set implementations in Java: HashSet, TreeSet Java's set implementations have been optimized so that it is very fast to search for elements in them

Java Set interface interface java.util.Set<T> has the following methods: they are exactly those of the Collection interface boolean containsAll(Collection c); boolean addAll(Collection c); boolean removeAll(Collection c); boolean retainAll(Collection c); void clear(); T[] toArray(); T[] toArray(T[] a); int size(); boolean isEmpty(); boolean contains(T e); boolean add(T e); boolean remove(T e); Iterator iterator();

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?

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

Typical set operations sometimes it is useful to compare sets: subset: S1 is a subset of S2 if S2 contains every element from S1. containsAll tests for subset relationship it can be useful to combine sets in the following ways: union: S1 union S2 contains all elements that are in S1 or S2. addAll performs set union intersection: S1 intersect S2 contains only the elements that are in both S1 and S2. retainAll performs set intersection difference: S1 difference S2 contains the elements that are in S1 that are not in S2. removeAll performs set difference Testing if s2 is a subset of s1 s1.containsAll(s2) Setting s1 to the union of s1 and s2 s1.addAll(s2) Setting s1 to the intersection of s1 and s2 s1.retainAll(s2) Setting s1 to the set difference of s1 and s2 s1.removeAll(s2)

Set practice problems 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.) Write the Moby Dick word testing program.

Set implementation Should we implement a set using a list? lists are bad for certain operations insertion at arbitrary index: add(index, element) searching for an element: contains(element), indexOf(element) removal from arbitrary index: remove(index) all these operations are O(n) on lists! (bad) use a balanced binary search tree to implement them!

Java Collections Framework

Java Set interface interface java.util.Set<T> has the following methods: (they are exactly those of the Collection interface) public boolean add(T e); public boolean addAll(Collection c); public void clear(); public boolean contains(T e); public boolean containsAll(Collection c); public boolean isEmpty(); public Iterator iterator(); public boolean remove(T e); public boolean removeAll(Collection c); public boolean retainAll(Collection c); public int size(); public T[] toArray(); public T[] toArray(T[] a);

Set implementations in Java Set is an interface; you can't say new Set() There are two implementations: TreeSet: a (balanced) BST storing elements HashSet: a hash table storing the elements we have essentially implemented TreeSet Java's set implementations have been optimized so that it is very fast to search for elements in them HashSet is faster than TreeSet for most operations

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" --> "692-4540" "Jenny" --> "867-5309" How would we do this with a list (or list(s))? A list doesn't map people to phone numbers; it maps ints 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?

A new ADT: 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 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: dictionaries associative arrays (depending on implementation) tables, hashes, hash tables

Java's Map interface Note that there are 2 generic types here! public interface Map<K,V> { public V put(K key, V value); public V get(K key); public V remove(K key); public boolean containsKey(K key); public boolean containsValue(V value); public int size(); public boolean isEmpty(); public void putAll(Map<K,V> map); public void clear(); public Set<K> keySet(); public Collection<V> values(); } Basic ops Bulk ops Collection views Note that there are 2 generic types here!

Implementing Map with a tree Make a BST of entries, sorted on the keys. Each entry also contains the associated value

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

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

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?)

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<K> keyItr = grades.keySet().iterator(); Iterator<V> 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());

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

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

Map Usage Summary Maps manipulate keys rather than the entire object Useful because allow collections collections to be smaller, more efficient, and easier to manage also allows for the same object to be part of multiple collections by having keys in each

TreeSet and TreeMap details Both the TreeSet and TreeMap classes are red/black tree implementations of a balanced binary search tree Operations, as listed from Lewis and Chase, are in the next tables. The tables do not list the generic types version (the tables reflect Java 1.4.2, not 1.5).

TABLE 13.1 Operations on a TreeSet

TABLE 13.2 Operations on a TreeMap

References Lewis & Chase book, End of chapter 13. Java API (available online)