Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using.

Similar presentations


Presentation on theme: "© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using."— Presentation transcript:

1 © 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using Data Structures Third Edition John Lewis & Joseph Chase

2 1-2 © 2010 Pearson Addison-Wesley. All rights reserved. 1-2 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

3 1-3 © 2010 Pearson Addison-Wesley. All rights reserved. 1-3 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

4 1-4 © 2010 Pearson Addison-Wesley. All rights reserved. 1-4 The conceptual view of a set collection

5 1-5 © 2010 Pearson Addison-Wesley. All rights reserved. 1-5 The operations on a set collection

6 1-6 © 2010 Pearson Addison-Wesley. All rights reserved. 1-6 A SetADT /** * SetADT defines the interface to a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ package jss2; import java.util.Iterator; public interface SetADT { /** * Adds one element to this set, ignoring duplicates. * * @param element the element to be added to this set */ public void add (T element); /** * SetADT defines the interface to a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ package jss2; import java.util.Iterator; public interface SetADT { /** * Adds one element to this set, ignoring duplicates. * * @param element the element to be added to this set */ public void add (T element);

7 1-7 © 2010 Pearson Addison-Wesley. All rights reserved. 1-7 A SetADT (continued) /** * Removes and returns a random element from this set. * * @return a random element from this set */ public T removeRandom (); /** * 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 SetADT union (SetADT set); /** * Removes and returns a random element from this set. * * @return a random element from this set */ public T removeRandom (); /** * 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 SetADT union (SetADT set);

8 1-8 © 2010 Pearson Addison-Wesley. All rights reserved. 1-8 A SetADT (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 (SetADT set); /** * Returns true if this set contains no elements * * @return true if this set contains no elements */ public boolean isEmpty(); /** * 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 (SetADT set); /** * Returns true if this set contains no elements * * @return true if this set contains no elements */ public boolean isEmpty();

9 1-9 © 2010 Pearson Addison-Wesley. All rights reserved. 1-9 A SetADT (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 iterator(); /** * Returns a string representation of this set * * @return a string representation of this set */ public String toString(); } /** * 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 iterator(); /** * Returns a string representation of this set * * @return a string representation of this set */ public String toString(); }

10 1-10 © 2010 Pearson Addison-Wesley. All rights reserved. 1-10 UML description of the SetADT interface

11 1-11 © 2010 Pearson Addison-Wesley. All rights reserved. 1-11 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

12 1-12 © 2010 Pearson Addison-Wesley. All rights reserved. 1-12 A bingo card

13 1-13 © 2010 Pearson Addison-Wesley. All rights reserved. 1-13 BINGO A set is an appropriate collection for BINGO, allowing the caller to pick numbers at random We create an object of class BingoBall to represent one letter/number combination The main program creates the balls, stores them in a set, and draws them at random

14 1-14 © 2010 Pearson Addison-Wesley. All rights reserved. 1-14 The BingoBall class /** * BingoBall represents a ball used in a Bingo game. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ public class BingoBall { 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 */ /** * BingoBall represents a ball used in a Bingo game. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ public class BingoBall { 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 */

15 1-15 © 2010 Pearson Addison-Wesley. All rights reserved. 1-15 The BingoBall class (continued) public BingoBall (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'; } public BingoBall (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'; }

16 1-16 © 2010 Pearson Addison-Wesley. All rights reserved. 1-16 The BingoBall class (continued) /** * Returns a string representation of this bingo ball. * * @return a string representation of the bingo ball */ public String toString () { return (letter + " " + number); } /** * Returns a string representation of this bingo ball. * * @return a string representation of the bingo ball */ public String toString () { return (letter + " " + number); }

17 1-17 © 2010 Pearson Addison-Wesley. All rights reserved. 1-17 The Bingo class /** * Bingo demonstrates the use of a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ import jss2.ArraySet; 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; ArraySet bingoSet = new ArraySet (); BingoBall ball; /** * Bingo demonstrates the use of a set collection. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ import jss2.ArraySet; 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; ArraySet bingoSet = new ArraySet (); BingoBall ball;

18 1-18 © 2010 Pearson Addison-Wesley. All rights reserved. 1-18 The Bingo class (continued) for (int num = 1; num <= NUM_BALLS; num++) { ball = new BingoBall (num); bingoSet.add (ball); } System.out.println ("Size: " + bingoSet.size()); System.out.println (); for (int num = 1; num <= NUM_PULLS; num++) { ball = bingoSet.removeRandom(); System.out.println (ball); } for (int num = 1; num <= NUM_BALLS; num++) { ball = new BingoBall (num); bingoSet.add (ball); } System.out.println ("Size: " + bingoSet.size()); System.out.println (); for (int num = 1; num <= NUM_PULLS; num++) { ball = bingoSet.removeRandom(); System.out.println (ball); }

19 1-19 © 2010 Pearson Addison-Wesley. All rights reserved. 1-19 UML description of the Bingo and BingoBall classes

20 1-20 © 2010 Pearson Addison-Wesley. All rights reserved. 1-20 Implementing a set with arrays The ArraySet 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

21 1-21 © 2010 Pearson Addison-Wesley. All rights reserved. 1-21 An array implementation of a set

22 1-22 © 2010 Pearson Addison-Wesley. All rights reserved. 1-22 The ArraySet class /** * ArraySet represents an array implementation of a set. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ package jss2; import jss2.exceptions.*; import java.util.*; public class ArraySet implements SetADT, Iterable { 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; /** * ArraySet represents an array implementation of a set. * * @author Dr. Lewis * @author Dr. Chase * @version 1.0, 9/21/2008 */ package jss2; import jss2.exceptions.*; import java.util.*; public class ArraySet implements SetADT, Iterable { 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;

23 1-23 © 2010 Pearson Addison-Wesley. All rights reserved. 1-23 The ArraySet class - constructors /** * Creates an empty set using the default capacity. */ public ArraySet() { count = 0; contents = (T[])(new Object[DEFAULT_CAPACITY]); } /** * Creates an empty set using the specified capacity. * * @param initialCapacity the initial capacity for the array set */ public ArraySet (int initialCapacity) { count = 0; contents = (T[])(new Object[initialCapacity]); } /** * Creates an empty set using the default capacity. */ public ArraySet() { count = 0; contents = (T[])(new Object[DEFAULT_CAPACITY]); } /** * Creates an empty set using the specified capacity. * * @param initialCapacity the initial capacity for the array set */ public ArraySet (int initialCapacity) { count = 0; contents = (T[])(new Object[initialCapacity]); }

24 1-24 © 2010 Pearson Addison-Wesley. All rights reserved. 1-24 The ArraySet 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) expandCapacity(); contents[count] = element; count++; } /** * 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) expandCapacity(); contents[count] = element; count++; }

25 1-25 © 2010 Pearson Addison-Wesley. All rights reserved. 1-25 The ArraySet class - addAll /** * Adds the contents of the parameter to this set. * * @param set the collection to be added to this set */ public void addAll (SetADT set) { Iterator scan = set.iterator(); while (scan.hasNext()) add (scan.next()); } /** * Adds the contents of the parameter to this set. * * @param set the collection to be added to this set */ public void addAll (SetADT set) { Iterator scan = set.iterator(); while (scan.hasNext()) add (scan.next()); }

26 1-26 © 2010 Pearson Addison-Wesley. All rights reserved. 1-26 The ArraySet class - removeRandom /** * Removes a random element from the set and returns it. Throws * an EmptyCollectionException if the set is empty. * * @return a random element from the set * @throws EmptyCollectionException if an empty set exception occurs */ public T removeRandom() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); int choice = rand.nextInt(count); T result = contents[choice]; contents[choice] = contents[count-1]; // fill the gap contents[count-1] = null; count--; return result; } /** * Removes a random element from the set and returns it. Throws * an EmptyCollectionException if the set is empty. * * @return a random element from the set * @throws EmptyCollectionException if an empty set exception occurs */ public T removeRandom() throws EmptyCollectionException { if (isEmpty()) throw new EmptyCollectionException("Stack"); int choice = rand.nextInt(count); T result = contents[choice]; contents[choice] = contents[count-1]; // fill the gap contents[count-1] = null; count--; return result; }

27 1-27 © 2010 Pearson Addison-Wesley. All rights reserved. 1-27 The ArraySet class - remove /** * Removes the specified element from the set and returns it. * Throws an EmptyCollectionException if the set is empty and a * NoSuchElementException 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 EmptyCollectionException if an empty set exception occurs * @throws NoSuchElementException if a no such element exception occurs */ public T remove (T target) throws EmptyCollectionException, NoSuchElementException { int search = NOT_FOUND; if (isEmpty()) throw new EmptyCollectionException("Stack"); /** * Removes the specified element from the set and returns it. * Throws an EmptyCollectionException if the set is empty and a * NoSuchElementException 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 EmptyCollectionException if an empty set exception occurs * @throws NoSuchElementException if a no such element exception occurs */ public T remove (T target) throws EmptyCollectionException, NoSuchElementException { int search = NOT_FOUND; if (isEmpty()) throw new EmptyCollectionException("Stack");

28 1-28 © 2010 Pearson Addison-Wesley. All rights reserved. 1-28 The ArraySet 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 NoSuchElementException(); T result = contents[search]; contents[search] = contents[count-1]; contents[count-1] = null; count--; return result; } for (int index=0; index < count && search == NOT_FOUND; index++) if (contents[index].equals(target)) search = index; if (search == NOT_FOUND) throw new NoSuchElementException(); T result = contents[search]; contents[search] = contents[count-1]; contents[count-1] = null; count--; return result; }

29 1-29 © 2010 Pearson Addison-Wesley. All rights reserved. 1-29 The ArraySet 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 that is the union of this set and * the parameter */ public SetADT union (SetADT set) { ArraySet both = new ArraySet (); for (int index = 0; index < count; index++) both.add (contents[index]); Iterator scan = set.iterator(); while (scan.hasNext()) both.add (scan.next()); return both; } /** * 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 that is the union of this set and * the parameter */ public SetADT union (SetADT set) { ArraySet both = new ArraySet (); for (int index = 0; index < count; index++) both.add (contents[index]); Iterator scan = set.iterator(); while (scan.hasNext()) both.add (scan.next()); return both; }

30 1-30 © 2010 Pearson Addison-Wesley. All rights reserved. 1-30 The ArraySet 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); } /** * 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); }

31 1-31 © 2010 Pearson Addison-Wesley. All rights reserved. 1-31 The ArraySet 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 (SetADT set) { boolean result = false; ArraySet temp1 = new ArraySet (); ArraySet temp2 = new ArraySet (); T obj; if (size() == set.size()) { temp1.addAll(this); temp2.addAll(set); /** * 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 (SetADT set) { boolean result = false; ArraySet temp1 = new ArraySet (); ArraySet temp2 = new ArraySet (); T obj; if (size() == set.size()) { temp1.addAll(this); temp2.addAll(set);

32 1-32 © 2010 Pearson Addison-Wesley. All rights reserved. 1-32 The ArraySet class – equals (cont.) while (scan.hasNext()) { obj = scan.next(); if (temp1.contains(obj)) { temp1.remove(obj); temp2.remove(obj); } result = (temp1.isEmpty() && temp2.isEmpty()); } return result; } while (scan.hasNext()) { obj = scan.next(); if (temp1.contains(obj)) { temp1.remove(obj); temp2.remove(obj); } result = (temp1.isEmpty() && temp2.isEmpty()); } return result; }

33 1-33 © 2010 Pearson Addison-Wesley. All rights reserved. 1-33 Complete UML description of the bingo system

34 1-34 © 2010 Pearson Addison-Wesley. All rights reserved. 1-34 A linked implementation of a set collection

35 1-35 © 2010 Pearson Addison-Wesley. All rights reserved. 1-35 The LinkedSet class /** * LinkedSet represents a linked implementation of a set. * * @author Dr. Chase * @author Dr. Lewis * @version 1.0, 9/21/2008 */ package jss2; import jss2.exceptions.*; import java.util.*; public class LinkedSet implements SetADT, Iterable { private static Random rand = new Random(); private int count; // the current number of elements in the set private LinearNode contents; /** * Creates an empty set. */ public LinkedSet() { count = 0; contents = null; } /** * LinkedSet represents a linked implementation of a set. * * @author Dr. Chase * @author Dr. Lewis * @version 1.0, 9/21/2008 */ package jss2; import jss2.exceptions.*; import java.util.*; public class LinkedSet implements SetADT, Iterable { private static Random rand = new Random(); private int count; // the current number of elements in the set private LinearNode contents; /** * Creates an empty set. */ public LinkedSet() { count = 0; contents = null; }

36 1-36 © 2010 Pearson Addison-Wesley. All rights reserved. 1-36 The LinkedSet 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))) { LinearNode node = new LinearNode (element); node.setNext(contents); contents = node; count++; } /** * 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))) { LinearNode node = new LinearNode (element); node.setNext(contents); contents = node; count++; }

37 1-37 © 2010 Pearson Addison-Wesley. All rights reserved. 1-37 The LinkedSet class – removeRandom /** * Removes and returns a random element from this set. Throws * an EmptySetException if the set contains no elements. * * @return a random element from this set * @throws EmptyCollectionException if an empty set exception occurs */ public T removeRandom() throws EmptyCollectionException { LinearNode previous, current; T result = null; if (isEmpty()) throw new EmptyCollectionException("Stack"); int choice = rand.nextInt(count) + 1; /** * Removes and returns a random element from this set. Throws * an EmptySetException if the set contains no elements. * * @return a random element from this set * @throws EmptyCollectionException if an empty set exception occurs */ public T removeRandom() throws EmptyCollectionException { LinearNode previous, current; T result = null; if (isEmpty()) throw new EmptyCollectionException("Stack"); int choice = rand.nextInt(count) + 1;

38 1-38 © 2010 Pearson Addison-Wesley. All rights reserved. 1-38 The LinkedSet class – removeRandom (continued) if (choice == 1) { result = contents.getElement(); contents = contents.getNext(); } else { previous = contents; for (int skip=2; skip < choice; skip++) previous = previous.getNext(); current = previous.getNext(); result = current.getElement(); previous.setNext(current.getNext()); } count--; return result; } if (choice == 1) { result = contents.getElement(); contents = contents.getNext(); } else { previous = contents; for (int skip=2; skip < choice; skip++) previous = previous.getNext(); current = previous.getNext(); result = current.getElement(); previous.setNext(current.getNext()); } count--; return result; }

39 1-39 © 2010 Pearson Addison-Wesley. All rights reserved. 1-39 The LinkedSet class – remove /** * Removes and returns the specified element from this set. * Throws an EmptySetException if the set is empty and a * NoSuchElemetnException 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 EmptyCollectionException if an empty set exception occurs * @throws NoSuchElementException if a no such element exception occurs */ public T remove (T target) throws EmptyCollectionException, NoSuchElementException { boolean found = false; LinearNode previous, current; T result = null; /** * Removes and returns the specified element from this set. * Throws an EmptySetException if the set is empty and a * NoSuchElemetnException 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 EmptyCollectionException if an empty set exception occurs * @throws NoSuchElementException if a no such element exception occurs */ public T remove (T target) throws EmptyCollectionException, NoSuchElementException { boolean found = false; LinearNode previous, current; T result = null;

40 1-40 © 2010 Pearson Addison-Wesley. All rights reserved. 1-40 The LinkedSet class – remove (cont.) if (contents.getElement().equals(target)) { result = contents.getElement(); contents = contents.getNext(); } else { previous = contents; current = contents.getNext(); for (int look=0; look < count && !found; look++) if (current.getElement().equals(target)) found = true; else { previous = current; current = current.getNext(); } if (contents.getElement().equals(target)) { result = contents.getElement(); contents = contents.getNext(); } else { previous = contents; current = contents.getNext(); for (int look=0; look < count && !found; look++) if (current.getElement().equals(target)) found = true; else { previous = current; current = current.getNext(); }

41 1-41 © 2010 Pearson Addison-Wesley. All rights reserved. 1-41 The LinkedSet class – remove (cont.) if (!found) throw new NoSuchElementException(); result = current.getElement(); previous.setNext(current.getNext()); } count--; return result; } if (!found) throw new NoSuchElementException(); result = current.getElement(); previous.setNext(current.getNext()); } count--; return result; }

42 1-42 © 2010 Pearson Addison-Wesley. All rights reserved. 1-42 Sets and Maps in the Java Collections API In Chapter 10, we discussed the TreeSet and TreeMap classes as well as the difference between a set and a map in JavaTreeSet TreeMap In Chapter 14, we continued that discussion with the discussion of the various hashing implementations (Hashtable, HashMap, HashSet, IdentityHashMap, LinkedHashSet, LinkedHashMap, WeakHashMap)HashtableHashMapHashSetIdentityHashMap LinkedHashSetLinkedHashMapWeakHashMap All of these are implementations of either the java.util.Set or java.util.Map interfaces java.util.Set java.util.Map Unlike our version which is designed to behave like an algebraic set, these Java implementations are simply generic collections


Download ppt "© 2010 Pearson Addison-Wesley. All rights reserved. Addison Wesley is an imprint of CHAPTER 15: Sets and Maps Java Software Structures: Designing and Using."

Similar presentations


Ads by Google