Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS-2852 Data Structures LECTURE 15 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com.

Similar presentations


Presentation on theme: "CS-2852 Data Structures LECTURE 15 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com."— Presentation transcript:

1 CS-2852 Data Structures LECTURE 15 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com

2 CS-2852 Data Structures, Andrew J. Wozniewicz Agenda Maps (Dictionaries) Sets

3 CS-2852 Data Structures, Andrew J. Wozniewicz Java Collections Framework Core Collection Interfaces Collection Iterable List Set SortedSet Queue Map SortedMap NavigableMap E E E E E E E E E NavigableSet E BlockingQueue E TransferQueue E Deque E

4 CS-2852 Data Structures, Andrew J. Wozniewicz Set Models the mathematical set abstraction Set interface does not introduce any new operations on top of Collection Adds restriction that duplicate elements are prohibited. Stronger contract on the behavior of the equals and hashCode operations: – Two instances are equal if they contain the same elements Set is a Collection that cannot contain duplicate elements. DEFINITION

5 CS-2852 Data Structures, Andrew J. Wozniewicz Set Interface public interface Set extends Collection {}

6 CS-2852 Data Structures, Andrew J. Wozniewicz Collection Interface public interface Collection extends Iterable { // Inherited operations Iterator iterator(); // Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional // Bulk operations boolean containsAll(Collection c); boolean addAll(Collection c); //optional boolean removeAll(Collection c); //optional boolean retainAll(Collection c); //optional void clear(); //optional // Array operations Object[] toArray(); T[] toArray(T[] a); }

7 CS-2852 Data Structures, Andrew J. Wozniewicz Set Interface public interface Set extends Collection {} Three concrete implementations in Java Collections Framework:  HashSet (based on HashMap)  TreeSet (based on TreeMap, R-B tree)  LinkedHashSet

8 CS-2852 Data Structures, Andrew J. Wozniewicz HashSet Boolean add(E e) Adds the specified element to this set if it is not already present. Void clear() Removes all of the elements from this set. Object clone() Returns a shallow copy of this HashSet instance: the elements themselves are not cloned. Boolean contains(Object o) Returns true if this set contains the specified element. Boolean isEmpty() Returns true if this set contains no elements. Iterator iterator() Returns an iterator over the elements in this set. Boolean remove( Object o) Removes the specified element from this set if it is present. Int size() Returns the number of elements in this set (its cardinality).

9 CS-2852 Data Structures, Andrew J. Wozniewicz HashSet Example public class SetDemo { public static void main(String[] argv) { Set h = new HashSet(); h.add("One"); h.add("Two"); h.add("One"); // DUPLICATE h.add("Three"); Iterator it = h.iterator(); while (it.hasNext()) { System.out.println(it.next()); }

10 CS-2852 Data Structures, Andrew J. Wozniewicz LinkedHashSet Hash-table and linked-list implementation of the Set interface. Predictable iteration order: the order in which the elements were inserted into the set. Maintains a doubly-linked list running through all of its entries. Constant-time performance for the basic add/remove/contains operations.

11 CS-2852 Data Structures, Andrew J. Wozniewicz Set Example // : c11:Set1.java // Things you can do with Sets. // From 'Thinking in Java, 3rd ed.' (c) Bruce Eckel 2002 // www.BruceEckel.com. See copyright notice in CopyRight.txt. import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.TreeSet; public class Set1 { static void fill(Set s) { s.addAll(Arrays.asList("one two three four five six seven".split(" "))); } // Code follows on the next slide... } ///:~

12 CS-2852 Data Structures, Andrew J. Wozniewicz Set Example - Continued public static void test(Set s) { // Strip qualifiers from class name: System.out.println("\n"+s.getClass().getName().replaceAll("\\w+\\.", "")); fill(s); System.out.println(s); // No duplicates! // Add another set to this one: s.addAll(s); s.add("one"); System.out.println(s); // Look something up: System.out.println("s.contains(\"one\"): " + s.contains("one")); } public static void main(String[] args) { test(new HashSet()); test(new TreeSet()); test(new LinkedHashSet()); }

13 CS-2852 Data Structures, Andrew J. Wozniewicz String.replaceAll(regex, …) ConstructDescription. Any character (may or may not match line terminators) \dA digit: [0-9] \DA non-digit: [^0-9] \s A whitespace character: [ \t\n\x0B\f\r] \SA non-whitespace character: [^\s] \wA word character: [a-zA-Z_0-9] \WA non-word character: [^\w] \Quotes the following character

14 CS-2852 Data Structures, Andrew J. Wozniewicz Set Example - Outputs HashSet [two, seven, five, one, three, four, six] s.contains("one"): true TreeSet [five, four, one, seven, six, three, two] s.contains("one"): true LinkedHashSet [one, two, three, four, five, six, seven] s.contains("one"): true

15 CS-2852 Data Structures, Andrew J. Wozniewicz Set Intersection import java.util.*; public abstract class SetUtils { public static boolean containsAny(Set a, Set b) { for (Iterator iter = b.iterator(); iter.hasNext(); ) { if (a.contains(iter.next())) { return true; } return false; } public static Set intersection(Set a, Set b) { Set c = new HashSet(); for (Iterator iter = b.iterator(); iter.hasNext(); ) { Object e = iter.next(); if (a.contains(e)) { c.add(e); } return c; } @author Oliver Steele

16 CS-2852 Data Structures, Andrew J. Wozniewicz Set Subtraction import java.util.HashSet; import java.util.Set; public class FindDupsAndUnique { public static void main(String args[]) { Set uniques = new HashSet(); Set dups = new HashSet(); String[] values = new String[] { "java", "kawa", "lava", "mewa", "java" }; for (int i = 0; i < values.length; i++) if (!uniques.add(values[i])) dups.add(values[i]); uniques.removeAll(dups); // Destructive set-difference System.out.println("Unique words: " + uniques); System.out.println("Duplicate words: " + dups); } Unique words: [kawa, lava, mewa] Duplicate words: [java]

17 CS-2852 Data Structures, Andrew J. Wozniewicz NavigableSet<E> public abstract interface NavigableSet extends SortedSet { E lower(Object arg0); // strictly less E floor(Object arg0); // greatest lower E ceiling(Object arg0); // E higher(Object arg0); E pollFirst(); E first(); E pollLast(); E last(); Iterator iterator(); NavigableSet descendingSet(); Iterator descendingIterator(); NavigableSet subSet(E fromElt, boolean fromIncl, E toElt, boolean toIncl); NavigableSet headSet(E fromElt, boolean fromIncl); NavigableSet tailSet(E toElt, boolean toIncl); SortedSet subSet(E fromElt, E toElt); SortedSet headSet(E elt); SortedSet tailSet(E elt); }

18 CS-2852 Data Structures, Andrew J. Wozniewicz NavigableSet: tailSet and headSet import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; public class Tail { public static void main(String args[]) throws Exception { String elements[] = { "Ireland", "Poland", "England", "Greenland", "Swasiland" }; SortedSet set = new TreeSet(Arrays.asList(elements)); System.out.println(set.tailSet("Ireland")); System.out.println(set.headSet("Ireland")); System.out.println(set.headSet("Ireland\0")); System.out.println(set.tailSet("Ireland\0")); System.out.println(set.subSet("Ireland", "Poland\0")); System.out.println(set.subSet("Ireland", "Ireland\0")); System.out.println(set.subSet("Ireland", "Ireland")); } [Ireland, Poland, Swasiland] [England, Greenland] [England, Greenland, Ireland] [Poland, Swasiland] [Ireland, Poland] [Ireland] []

19 CS-2852 Data Structures, Andrew J. Wozniewicz Map Cannot contain duplicate keys: each key maps to at most 1 value A.k.a “Dictionary”, “Associative Array” “Dictionary” is an abstract class – parent of any classthat maps keys to values (e.g. Hashtable) An object that maps keys to values. DEFINITION

20 CS-2852 Data Structures, Andrew J. Wozniewicz Map Interface public interface Map { // Basic operations V put(K key, V value); V get(Object key); V remove(Object key); boolean containsKey(Object key); boolean containsValue(Object value); int size(); boolean isEmpty(); // Bulk operations void putAll(Map m); void clear(); // Collection Views public Set keySet(); public Collection values(); public Set > entrySet(); // Interface for entrySet elements public interface Entry { K getKey(); V getValue(); V setValue(V value); }

21 CS-2852 Data Structures, Andrew J. Wozniewicz Map Interface Map provides Collection views Allows iteration over keys, values, and key-value pairs Provides a safe way to remove entries during iteration The key methods: containsKey and containsValue

22 CS-2852 Data Structures, Andrew J. Wozniewicz Map Interface Three concrete implementations in Java Collections Framework:  HashMap  No guarantees about order of elements  TreeMap  Orders elements by keys  LinkedHashMap  Preserves order of insertion

23 CS-2852 Data Structures, Andrew J. Wozniewicz Iterating Over Keys for (KeyType key : m.keySet()) System.out.println(key); // Filter a map based on some property of its keys. for (Iterator it = m.keySet().iterator(); it.hasNext(); ) if (it.next().isBogus()) it.remove();

24 CS-2852 Data Structures, Andrew J. Wozniewicz Iterating Over Key-Value Pairs for (Map.Entry e : m.entrySet()) System.out.println(e.getKey() + ": " + e.getValue());

25 CS-2852 Data Structures, Andrew J. Wozniewicz Map Collections Views Calling Iterator’s remove is generally permitted Also permitted Collection’s bulk removal operations: – remove – removeAll – clear NO SUPPORT for element addition while iterating

26 CS-2852 Data Structures, Andrew J. Wozniewicz HashMap Class HashTable-based implementation of the Map interface Permits null values and key Makes no guarantees about the ordering in the Map Constant-time performance for the basic operations: get, put (provided the hash function is good) Capacity (16) and LoadFactor (0.75) – ctor parameters

27 CS-2852 Data Structures, Andrew J. Wozniewicz HashMap Example import java.util.*; public class Freq { public static void main(String[] args) { Map m = new HashMap (); // Initialize frequency table from command line for (String a : args) { Integer freq = m.get(a); m.put(a, (freq == null) ? 1 : freq + 1); } System.out.println(m.size() + " distinct words:"); System.out.println(m); }

28 CS-2852 Data Structures, Andrew J. Wozniewicz Hash Map Example – Output java Freq if it is to be it is up to me to delegate 8 distinct words: {to=3, delegate=1, be=1, it=2, up=1, if=1, me=1, is=2}

29 CS-2852 Data Structures, Andrew J. Wozniewicz HashMap Example II import java.util.*; class HashMapDemo { public static void main(String args[]) { // Create a hash map Map hm = new HashMap (); // Put elements to the map hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = ((Double)hm.get("John Doe")).doubleValue(); hm.put("John Doe", new Double(balance + 1000)); System.out.println("John Doe's new balance: " + hm.get("John Doe")); } John Doe: 3434.34 Tom Smith: 123.22 Jane Baker: 1378.0 Todd Hall: 99.22 Ralph Smith: -19.08 John Doe's new balance: 4434.34

30 CS-2852 Data Structures, Andrew J. Wozniewicz TreeMap Example import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class Main { public static void main(String[] argv) throws Exception { Map map = new HashMap (); map = new TreeMap(); map.put("a", new Integer(1)); map.put("b", new Integer(2)); map.put("c", new Integer(3)); int size = map.size(); // 2 // More code to follow }

31 CS-2852 Data Structures, Andrew J. Wozniewicz TreeMap Example public class Main { public static void main(String[] argv) throws Exception { // Insert code from previous slide here Object oldValue = map.put("a", new Integer(9)); // 1 oldValue = map.remove("c"); // 3 Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); System.out.println(key); } it = map.values().iterator(); while (it.hasNext()) { Object value = it.next(); System.out.println(value); }

32 CS-2852 Data Structures, Andrew J. Wozniewicz LinkedHashMap Example import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; public class LinkedHashMapTest { public static void main(String[] argv) throws Exception { Map map = new LinkedHashMap (); map.put("3", "value3"); map.put("2", "value2"); map.put("1", "value1"); map.put("2", "value4"); for (Iterator it = map.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = map.get(key); System.out.print(key+" "); } 3 2 1

33 CS-2852 Data Structures, Andrew J. Wozniewicz Map Example: Map of Arrays import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class MapArray { public static void main(String[] args) { Map map = new TreeMap (); int[] array = new int[3]; array[0] = 0; array[1] = 1; array[2] = 2; map.put("array1", array); array = new int[4]; array[0] = 6; array[1] = 7; array[2] = 8; array[3] = 9; map.put("array2", array); // More code follows... }

34 CS-2852 Data Structures, Andrew J. Wozniewicz Map Example: Map of Arrays import java.util.Iterator; import java.util.Map; import java.util.TreeMap; public class MapArray { // Code from previous slide goes here Iterator iter = map.keySet().iterator(); while (iter.hasNext()) { String arrayName = iter.next(); array = map.get(arrayName); System.out.print("\n" + arrayName + ": "); for (int i = 0; i < array.length; i++) { System.out.print(array[i]+" "); } array1: 0 1 2 array2: 6 7 8 9

35 Questions? Image copyright © 2010 andyjphoto.com


Download ppt "CS-2852 Data Structures LECTURE 15 Andrew J. Wozniewicz Image copyright © 2010 andyjphoto.com."

Similar presentations


Ads by Google