CHAPTER 15 Sets and Maps Java Software Structures










































- Slides: 42
CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using Data Structures Third Edition John Lewis & Joseph Chase Addison Wesley is an imprint of © 2010 Pearson Addison-Wesley. All rights reserved.
Chapter Objectives • • • Define set and map collections Use a set collection to solve a problem Examine an array implementation of a set Examine a linked implementation of a set Explore Java Collections API implementations of set and maps 1 -2 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -2
A Set Collection • Lets consider a collection based upon the idea of an algebraic set • Such a set collection does not allow duplicates and groups elements without regard to their relationship to each other • It's as if you threw them all in a box • You can reach into a box and pull out an element, and are equally likely to get any one • It is a nonlinear collection, but could be implemented with a linear data structure 1 -3 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -3
The conceptual view of a set collection 1 -4 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -4
The operations on a set collection 1 -5 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -5
A Set. ADT /** * Set. ADT defines the interface to a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1. 0, 9/21/2008 */ package jss 2; import java. util. Iterator; public interface Set. ADT<T> { /** * Adds one element to this set, ignoring duplicates. * * @param element the element to be added to this set */ public void add (T element); 1 -6 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -6
A Set. ADT (continued) /** * Removes and returns a random element from this set. * * @return a random element from this set */ public T remove. Random (); /** * Removes and returns the specified element from this set. * * @param element the element to be removed from this list * @return the element just removed from this list */ public T remove (T element); /** * Returns the union of this set and the parameter * * @param set the set to be unioned with this set * @return a set that is the union of this set and the parameter */ public Set. ADT<T> union (Set. ADT<T> set); 1 -7 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -7
A Set. ADT (continued) /** * Returns true if this set contains the parameter * * @param target the element being sought in this set * @return true if this set contains the parameter */ public boolean contains (T target); /** * Returns true if this set and the parameter contain exactly * the same elements * * @param set the set to be compared with this set * @return true if this set and the parameter contain exactly * the same elements */ public boolean equals (Set. ADT<T> set); /** * Returns true if this set contains no elements * * @return true if this set contains no elements */ public boolean is. Empty(); © 2010 Pearson Addison-Wesley. All rights reserved. 1 -8
A Set. ADT (continued) /** * Returns the number of elements in this set * * @return the interger number of elements in this set */ public int size(); /** * Returns an iterator for the elements in this set * * @return an iterator for the elements in this set */ public Iterator<T> iterator(); /** * Returns a string representation of this set * * @return a string representation of this set */ public String to. String(); } 1 -9 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -9
UML description of the Set. ADT<T> interface 1 -10 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -10
Using a Set: BINGO • The game of BINGO can be used to demonstrate the use of a set collection • Each player has a bingo card with numeric values associated with the letters B-I-N-G-O • Letter/number combinations (on bingo balls) are picked at random, which the player marks on their card if possible • The first player to get five squares in a row wins 1 -11 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -11
A bingo card 1 -12 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -12
BINGO • A set is an appropriate collection for BINGO, allowing the caller to pick numbers at random • We create an object of class Bingo. Ball to represent one letter/number combination • The main program creates the balls, stores them in a set, and draws them at random 1 -13 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -13
The Bingo. Ball class /** * Bingo. Ball represents a ball used in a Bingo game. * * @author Dr. Lewis * @author Dr. Chase * @version 1. 0, 9/21/2008 */ public class Bingo. Ball { private char letter; private int number; /** * Sets up this Bingo ball with the specified number and the * appropriate letter. * * @param num the number to be applied to the new bingo ball */ 1 -14 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -14
The Bingo. Ball class (continued) public Bingo. Ball (int num) { number = num; if (num <= 15) letter = 'B'; else if (num <= 30) letter = 'I'; else if (num <= 45) letter = 'N'; else if (num <= 60) letter = 'G'; else letter = 'O'; } 1 -15 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -15
The Bingo. Ball class (continued) /** * Returns a string representation of this bingo ball. * * @return a string representation of the bingo ball */ public String to. String () { return (letter + " " + number); } } 1 -16 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -16
The Bingo class /** * Bingo demonstrates the use of a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1. 0, 9/21/2008 */ import jss 2. Array. Set; public class Bingo { /** * Creates all 75 Bingo balls and stores them in a set. Then * pulls several balls from the set at random and prints them. */ public static void main (String[] args) { final int NUM_BALLS = 75, NUM_PULLS = 10; Array. Set<Bingo. Ball> bingo. Set = new Array. Set<Bingo. Ball>(); Bingo. Ball ball; 1 -17 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -17
The Bingo class (continued) for (int num = 1; num <= NUM_BALLS; num++) { ball = new Bingo. Ball (num); bingo. Set. add (ball); } System. out. println ("Size: " + bingo. Set. size()); System. out. println (); for (int num = 1; num <= NUM_PULLS; num++) { ball = bingo. Set. remove. Random(); System. out. println (ball); } } } 1 -18 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -18
UML description of the Bingo and Bingo. Ball classes 1 -19 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -19
Implementing a set with arrays • The Array. Set class represents an array implementation of a set collection • Set elements are kept contiguously at one end of the array • An integer (count) represents: – the number of elements in the set – the next empty index in the array 1 -20 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -20
An array implementation of a set 1 -21 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -21
The Array. Set class /** * Array. Set represents an array implementation of a set. * * @author Dr. Lewis * @author Dr. Chase * @version 1. 0, 9/21/2008 */ package jss 2; import jss 2. exceptions. *; import java. util. *; public class Array. Set<T> implements Set. ADT<T>, Iterable<T> { private static Random rand = new Random(); private final int DEFAULT_CAPACITY = 100; private final int NOT_FOUND = -1; private int count; // the current number of elements in the set private T[] contents; 1 -22 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -22
The Array. Set class - constructors /** * Creates an empty set using the default capacity. */ public Array. Set() { count = 0; contents = (T[])(new Object[DEFAULT_CAPACITY]); } /** * Creates an empty set using the specified capacity. * * @param initial. Capacity the initial capacity for the array set */ public Array. Set (int initial. Capacity) { count = 0; contents = (T[])(new Object[initial. Capacity]); } 1 -23 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -23
The Array. Set class - add /** * Adds the specified element to the set if it is not already * present. Expands the capacity of the set array if necessary. * * @param element the element to be added to the set array */ public void add (T element) { if (!(contains(element))) { if (size() == contents. length) expand. Capacity(); contents[count] = element; count++; } } 1 -24 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -24
The Array. Set class - add. All /** * Adds the contents of the parameter to this set. * * @param set the collection to be added to this set */ public void add. All (Set. ADT<T> set) { Iterator<T> scan = set. iterator(); while (scan. has. Next()) add (scan. next()); } 1 -25 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -25
The Array. Set class - remove. Random /** * Removes a random element from the set and returns it. Throws * an Empty. Collection. Exception if the set is empty. * * @return a random element from the set * @throws Empty. Collection. Exception if an empty set exception occurs */ public T remove. Random() throws Empty. Collection. Exception { if (is. Empty()) throw new Empty. Collection. Exception("Stack"); int choice = rand. next. Int(count); T result = contents[choice]; contents[choice] = contents[count-1]; // fill the gap contents[count-1] = null; count--; return result; } 1 -26 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -26
The Array. Set class - remove /** * Removes the specified element from the set and returns it. * Throws an Empty. Collection. Exception if the set is empty and a * No. Such. Element. Exception if the target is not in the set. * * @param target the element being sought in the set * @return the element specified by the target * @throws Empty. Collection. Exception if an empty set exception occurs * @throws No. Such. Element. Exception if a no such element exception occurs */ public T remove (T target) throws Empty. Collection. Exception, No. Such. Element. Exception { int search = NOT_FOUND; if (is. Empty()) throw new Empty. Collection. Exception("Stack"); 1 -27 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -27
The Array. Set class – remove (cont. ) for (int index=0; index < count && search == NOT_FOUND; index++) if (contents[index]. equals(target)) search = index; if (search == NOT_FOUND) throw new No. Such. Element. Exception(); T result = contents[search]; contents[search] = contents[count-1]; contents[count-1] = null; count--; return result; } 1 -28 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -28
The Array. Set class – union /** * Returns a new set that is the union of this set and the * parameter. * * @param set the set that is to be unioned with this set * @return a new that is the union of this set and * the parameter */ public Set. ADT<T> union (Set. ADT<T> set) { Array. Set<T> both = new Array. Set<T>(); for (int index = 0; index < count; index++) both. add (contents[index]); Iterator<T> scan = set. iterator(); while (scan. has. Next()) both. add (scan. next()); return both; } 1 -29 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -29
The Array. Set class – contains /** * Returns true if this set contains the specified target * element. * * @param target the element being sought within this set * @return true if the set contains the target element */ public boolean contains (T target) { int search = NOT_FOUND; for (int index=0; index < count && search == NOT_FOUND; index++) if (contents[index]. equals(target)) search = index; return (search != NOT_FOUND); } 1 -30 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -30
The Array. Set class – equals /** * Returns true if this set contains exactly the same elements * as the parameter. * * @param set the set to be compared with this set * @return true if the parameter set and this set contain * exactly the same elements */ public boolean equals (Set. ADT<T> set) { boolean result = false; Array. Set<T> temp 1 = new Array. Set<T>(); Array. Set<T> temp 2 = new Array. Set<T>(); T obj; if (size() == set. size()) { temp 1. add. All(this); temp 2. add. All(set); 1 -31 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -31
The Array. Set class – equals (cont. ) while (scan. has. Next()) { obj = scan. next(); if (temp 1. contains(obj)) { temp 1. remove(obj); temp 2. remove(obj); } } result = (temp 1. is. Empty() && temp 2. is. Empty()); } return result; } 1 -32 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -32
Complete UML description of the bingo system 1 -33 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -33
A linked implementation of a set collection 1 -34 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -34
The Linked. Set class /** * Linked. Set represents a linked implementation of a set. * * @author Dr. Chase * @author Dr. Lewis * @version 1. 0, 9/21/2008 */ package jss 2; import jss 2. exceptions. *; import java. util. *; public class Linked. Set<T> implements Set. ADT<T>, Iterable<T> { private static Random rand = new Random(); private int count; // the current number of elements in the set private Linear. Node<T> contents; /** * Creates an empty set. */ public Linked. Set() { count = 0; contents = null; } © 2010 Pearson Addison-Wesley. All rights reserved. 1 -35
The Linked. Set class – add /** * Adds the specified element to this set if it is not already * present. * * @param element the element to be added to this set */ public void add (T element) { if (!(contains(element))) { Linear. Node<T> node = new Linear. Node<T> (element); node. set. Next(contents); contents = node; count++; } } 1 -36 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -36
The Linked. Set class – remove. Random /** * Removes and returns a random element from this set. Throws * an Empty. Set. Exception if the set contains no elements. * * @return a random element from this set * @throws Empty. Collection. Exception if an empty set exception occurs */ public T remove. Random() throws Empty. Collection. Exception { Linear. Node<T> previous, current; T result = null; if (is. Empty()) throw new Empty. Collection. Exception("Stack"); int choice = rand. next. Int(count) + 1; 1 -37 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -37
The Linked. Set class – remove. Random (continued) if (choice == 1) { result = contents. get. Element(); contents = contents. get. Next(); } else { previous = contents; for (int skip=2; skip < choice; skip++) previous = previous. get. Next(); current = previous. get. Next(); result = current. get. Element(); previous. set. Next(current. get. Next()); } count--; return result; } 1 -38 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -38
The Linked. Set class – remove /** * Removes and returns the specified element from this set. * Throws an Empty. Set. Exception if the set is empty and a * No. Such. Elemetn. Exception if the target is not in the set. * * @param target the element being sought in this set * @return the element just removed from this set * @throws Empty. Collection. Exception if an empty set exception occurs * @throws No. Such. Element. Exception if a no such element exception occurs */ public T remove (T target) throws Empty. Collection. Exception, No. Such. Element. Exception { boolean found = false; Linear. Node<T> previous, current; T result = null; 1 -39 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -39
The Linked. Set class – remove (cont. ) if (contents. get. Element(). equals(target)) { result = contents. get. Element(); contents = contents. get. Next(); } else { previous = contents; current = contents. get. Next(); for (int look=0; look < count && !found; look++) if (current. get. Element(). equals(target)) found = true; else { previous = current; current = current. get. Next(); } 1 -40 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -40
The Linked. Set class – remove (cont. ) if (!found) throw new No. Such. Element. Exception(); result = current. get. Element(); previous. set. Next(current. get. Next()); } count--; return result; } 1 -41 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -41
Sets and Maps in the Java Collections API • In Chapter 10, we discussed the Tree. Set and Tree. Map classes as well as the difference between a set and a map in Java • In Chapter 14, we continued that discussion with the discussion of the various hashing implementations (Hashtable, Hash. Map, Hash. Set, Identity. Hash. Map, Linked. Hash. Set, Linked. Hash. Map, Weak. Hash. Map) • All of these are implementations of either the java. util. Set or java. util. Map interfaces • Unlike our version which is designed to behave like an algebraic set, these Java implementations are simply generic collections 1 -42 © 2010 Pearson Addison-Wesley. All rights reserved. 1 -42