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.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 5 The Collections API.
Advertisements

Introduction to Computation and Problem Solving Class 32: The Java® Collections Framework Prof. Steven R. Lerman and Dr. V. Judson Harward.
11 Copyright © 2005, Oracle. All rights reserved. Using Arrays and Collections.
Java Programming: Advanced Topics 1 Collections and Utilities.
Transparency No. 1 Java Collection API : Built-in Data Structures for Java.
Building Java Programs Chapter 10
Concrete collections in Java library
JAVA Programming (Session 7) When you are willing to make sacrifices for a great cause, you will never be alone. Instructor:
Nyhoff, ADTs, Data Structures and Problem Solving with C++, Second Edition, © 2005 Pearson Education, Inc. All rights reserved Hash Tables,
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
The List ADT Textbook Sections
CE203 - Application Programming Autumn 2013CE203 Part 41 Part 4.
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Collections Framework A very brief look at Java’s Collection Framework David Davenport May 2010.
Collections Sets - no duplicates Lists - duplicates allowed Maps - key / value pairs A collection is an Object which contains other Objects. There are.
CSci 143 Sets & Maps Adapted from Marty Stepp, University of Washington
15-Jun-15 Lists in Java Part of the Collections Framework.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
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.
The Java Collections Package C. DeJong Fall 2001.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Chapter 19 Java Data Structures
Collections. Why collections? Collections are used to hold a collection of objects. List holds objects based on order of insertion and can hold non unique.
SEG4110 – Advanced Software Design and Reengineering TOPIC G Java Collections Framework.
Java Collections Framework A presentation by Eric Fabricant.
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.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
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.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Big Java Chapter 16.
Sets Recall from chapter 22 that one of the Collection subclasses is the Set – A Set is a list in which there are no duplicate entries, which you might.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Chapter 18 Java Collections Framework
1 TCSS 143, Autumn 2004 Lecture Notes Java Collection Framework: Maps and Sets.
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.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
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.
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.
1 Java's Collection Framework Map and Sets. 2 Collection Framework  A collections framework is a unified architecture for representing and manipulating.
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
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
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
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
Chapter 19 Java Data Structures
Introduction to Collections
Introduction to Collections
TCSS 342, Winter 2006 Lecture Notes
Introduction to Collections
Part of the Collections Framework
Introduction to Collections
Introduction to Collections
Part of the Collections Framework
Presentation transcript:

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 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[ ]);

3 Iterators for sets A set has a method Iterator iterator( ) to create an iterator over the set The iterator has the usual methods: boolean hasNext() Object next() void remove() Since sets have iterators, you can also use Java 5’s “enhanced for loop” remove() allows you to remove elements as you iterate over the set If you change the set in any other way during iteration, the iterator will throw a ConcurrentModificationException

4 Iterating through a Set (Java 1.4) import java.util.*; public class SetExample2 { public static void main(String[] args) { String[ ] words = { "When", "all", "is", "said", "and", "done", "more", "has", "been", "said", "than", "done" }; Set mySet = new HashSet(); for (int i = 0; i < words.length; i++) { mySet.add(words[i]); } for (Iterator iter = mySet.iterator(); iter.hasNext();) { String word = (String) iter.next(); System.out.print(word + " "); } System.out.println(); } } and has more When done all than said is been

5 Iterating through a Set (Java 5.0) import java.util.*; public class SetExample { public static void main(String[] args) { String[ ] words = { "When", "all", "is", "said", "and", "done", "more", "has", "been", "said", "than", "done" }; Set mySet = new HashSet (); for (String word : words) { mySet.add(word); } for (String word : mySet) { System.out.print(word + " "); } System.out.println(); } } and has more When done all than said is been

6 Set implementations Set is an interface; you can’t say new Set( ) There are four implementations: HashSet is best for most purposes TreeSet guarantees that an iterator will return elements in sorted order LinkedHashSet guarantees that guarantees that an iterator will return elements in the order they were inserted AbstractSet is a “helper” abstract class for new implementations It’s poor style to expose the implementation, so: Good: Set s = new HashSet( ); Fair: HashSet s = new HashSet( );

7 Typical set operations 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)

8 Set equality Object.equals(Object), inherited by all objects, really is an identity comparison Implementations of Set override equals so that sets are equal if they contain the same elements equals even works if two sets have different implementations equals is a test on entire sets; you have to be sure you have a working equals on individual set elements hashCode has been extended similarly This is for sets, not elements of a collection!

9 Membership testing in HashSets When testing whether a HashSet contains a given object, Java does this: Java computes the hash code for the given object Hash codes are discussed in a separate lecture Java compares the given object, using equals, only with elements in the set that have the same hash code 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 Moral: to use a HashSet properly, you must have a good public boolean equals(Object) and a good public int hashCode() defined for the elements of the set

10 The SortedSet interface A SortedSet is just like a Set, except that an Iterator will go through it in ascending order SortedSet is implemented by TreeSet

11 Membership testing in TreeSet s In a TreeSet, elements are kept in order That means Java must have some means of comparing elements to decide which is “larger” and which is “smaller” Java does this by using either: The int compareTo(Object) method of the Comparable interface, or The int compare(Object, Object) method of the Comparator interface Which method to use is determined when the TreeSet is constructed

12 Comparisons for TreeSet s new TreeSet() Uses the elements “natural order,” that is, it uses compareTo(Object) from Comparable All elements added to this TreeSet must implement Comparable, or you will get a ClassCastException new TreeSet(Comparator) Uses compare(Object, Object) from the given Comparator The Comparator specified in the constructor must be applicable to all elements added to this TreeSet, or you will get a ClassCastException Moral: to use a TreeSet properly, you must provide the equals method and implement either Comparable or Comparator for the elements of the set

13 How hard is it to use a Set ? You must have a working equals(Object) and a working hashCode() or comparison method If you don’t really care about iteration order, every object inherits equals(Object) and hashCode() from Object, and this is usually good enough That is, assuming you are happy with the == test String s do all this for you (they implement equals, hashCode, and Comparable ) Bottom line: If you don’t care about order, and == is good enough, just use HashSet

14 Set tips add and remove return true if they modify the set Here's a trick to remove duplicates from a Collection c : Collection noDups = new HashSet(c); A Set may not contain itself an an element Danger: The behavior of a set is undefined if you change an element to be equal to another element Danger: A TreeSet may throw a ConcurrentModificationException if you change an element in the TreeSet

15 The Map interface A Map is an object that maps keys to values A map cannot contain duplicate keys Each key can map to at most one value Examples: dictionary, phone book, etc.

16 Map implementations Map is an interface; you can’t say new Map( ) Here are two implementations: HashMap is the faster TreeMap guarantees the order of iteration It’s poor style to expose the implementation unnecessarily, so: Good: Map map = new HashMap( ); Fair: HashMap map = new HashMap( );

17 Map: Basic operations 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( );

18 More about put If the map already contains a given key, put(key, value) replaces the value associated with that key This means Java has to do equality testing on keys With a HashMap implementation, you need to define equals and hashCode for all your keys With a TreeMap implementation, you need to define equals and implement the Comparable interface for all your keys

19 Map: Bulk operations void putAll(Map t); Copies one Map into another Example: newMap.putAll(oldMap); void clear(); Example: oldMap.clear();

20 Map: Collection views public Set keySet( ); public Collection values( ); public Set entrySet( ); returns a set of Map.Entry (key-value) pairs You can create iterators for the key set, the value set, or the entry set (the set of entries, that is, key- value pairs) The above views provide the only way to iterate over a Map

21 Map example import java.util.*; public class MapExample { public static void main(String[] args) { Map fruit = new HashMap (); fruit.put("Apple", "red"); fruit.put("Pear", "yellow"); fruit.put("Plum", "purple"); fruit.put("Cherry", "red"); for (String key : fruit.keySet()) { System.out.println(key + ": " + fruit.get(key)); } } } Plum: purple Apple: red Pear: yellow Cherry: red

22 Map.Entry Interface for entrySet elements public interface Entry { // Inner interface of Map Object getKey( ); Object getValue( ); Object setValue(Object value); } This is a small interface for working with the Collection returned by entrySet( ) Can get elements only from the Iterator, and they are only valid during the iteration

23 The End