cs-2852 data structures lecture 15 andrew j. wozniewicz image copyright © 2010 andyjphoto.com
TRANSCRIPT
CS-2852 Data Structures, Andrew J. Wozniewicz
Java Collections Framework
Core Collection Interfaces
Collection
Iterable
ListSet
SortedSet
Queue
Map
SortedMap
NavigableMap
E
E
E E E
E
E
EE
NavigableSet
E
BlockingQueue
E
TransferQueue
E
DequeE
CS-2852 Data Structures, Andrew J. Wozniewicz
Set
• Models the mathematical set abstraction• Set<E> interface does not introduce any new
operations on top of Collection<E>• 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
CS-2852 Data Structures, Andrew J. Wozniewicz
Set<E> Interface
public interface Set<E> extends Collection<E>
{}
CS-2852 Data Structures, Andrew J. Wozniewicz
Collection<E> Interfacepublic interface Collection<E> extends Iterable<E> { // Inherited operations Iterator<E> 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<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional
// Array operations Object[] toArray(); <T> T[] toArray(T[] a);}
CS-2852 Data Structures, Andrew J. Wozniewicz
Set<E> Interface
public interface Set<E> extends Collection<E>
{}
• Three concrete implementations in Java Collections Framework: HashSet (based on HashMap) TreeSet (based on TreeMap, R-B tree)
LinkedHashSet
CS-2852 Data Structures, Andrew J. Wozniewicz
HashSetBoolean 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<E> 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).
CS-2852 Data Structures, Andrew J. Wozniewicz
HashSet Examplepublic 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()); } }}
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.
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...
} ///:~
CS-2852 Data Structures, Andrew J. Wozniewicz
Set Example - Continuedpublic static void test(Set s) { // Strip qualifiers from class name: System.out.println("\n"+s.getClass().getName() .replaceAll("\\w+\\.", "")); fill(s); fill(s); fill(s); System.out.println(s); // No duplicates! // Add another set to this one: s.addAll(s); s.add("one"); s.add("one"); 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()); }
CS-2852 Data Structures, Andrew J. Wozniewicz
String.replaceAll(regex, …)
Construct Description
. Any character (may or may not match line terminators)
\d A digit: [0-9]\D A non-digit: [^0-9]
\s A whitespace character: [ \t\n\x0B\f\r]
\S A non-whitespace character: [^\s]
\w A word character: [a-zA-Z_0-9]
\W A non-word character: [^\w]
\ Quotes the following character
CS-2852 Data Structures, Andrew J. Wozniewicz
Set Example - OutputsHashSet[two, seven, five, one, three, four, six][two, seven, five, one, three, four, six]s.contains("one"): true
TreeSet[five, four, one, seven, six, three, two][five, four, one, seven, six, three, two]s.contains("one"): true
LinkedHashSet[one, two, three, four, five, six, seven][one, two, three, four, five, six, seven]s.contains("one"): true
CS-2852 Data Structures, Andrew J. Wozniewicz
Set Intersectionimport 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; }}
@au
thor
Oliv
er S
teel
e
CS-2852 Data Structures, Andrew J. Wozniewicz
Set Subtractionimport 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]
CS-2852 Data Structures, Andrew J. Wozniewicz
NavigableSet<E>public abstract interface NavigableSet<E> extends SortedSet<E> { 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);}
CS-2852 Data Structures, Andrew J. Wozniewicz
NavigableSet: tailSet and headSetimport 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][]
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
CS-2852 Data Structures, Andrew J. Wozniewicz
Map<K, V> Interfacepublic interface Map<K,V> { // 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<? extends K, ? extends V> m); void clear(); // Collection Views public Set<K> keySet(); public Collection<V> values(); public Set<Map.Entry<K,V>> entrySet(); // Interface for entrySet elements public interface Entry { K getKey(); V getValue(); V setValue(V value); }}
CS-2852 Data Structures, Andrew J. Wozniewicz
Map<K,V> 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
CS-2852 Data Structures, Andrew J. Wozniewicz
Map<K,V> 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
CS-2852 Data Structures, Andrew J. Wozniewicz
Iterating Over Keysfor (KeyType key : m.keySet()) System.out.println(key);
// Filter a map based on some property of its keys.for (Iterator<Type> it = m.keySet().iterator(); it.hasNext(); ) if (it.next().isBogus()) it.remove();
CS-2852 Data Structures, Andrew J. Wozniewicz
Iterating Over Key-Value Pairs
for (Map.Entry<KeyType, ValType> e : m.entrySet()) System.out.println(e.getKey() + ": " + e.getValue());
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
CS-2852 Data Structures, Andrew J. Wozniewicz
HashMap<K,V> Class
• HashTable-based implementation of the Map<K,V> 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
CS-2852 Data Structures, Andrew J. Wozniewicz
HashMap Exampleimport java.util.*;
public class Freq { public static void main(String[] args) { Map<String, Integer> m = new HashMap<String, Integer>();
// 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); }}
CS-2852 Data Structures, Andrew J. Wozniewicz
Hash Map Example – Outputjava 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}
CS-2852 Data Structures, Andrew J. Wozniewicz
HashMap Example IIimport java.util.*; class HashMapDemo {
public static void main(String args[]) { // Create a hash map Map<String,Double> hm = new HashMap<String,Double>(); // 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.34Tom Smith: 123.22Jane Baker: 1378.0Todd Hall: 99.22Ralph Smith: -19.08
John Doe's new balance: 4434.34
CS-2852 Data Structures, Andrew J. Wozniewicz
TreeMap Exampleimport 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<String, Integer> map = new HashMap<String, Integer>(); 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 }}
CS-2852 Data Structures, Andrew J. Wozniewicz
TreeMap Examplepublic 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); } }}
CS-2852 Data Structures, Andrew J. Wozniewicz
LinkedHashMap Exampleimport java.util.Iterator;import java.util.LinkedHashMap;import java.util.Map;
public class LinkedHashMapTest { public static void main(String[] argv) throws Exception { Map<String, String> map = new LinkedHashMap<String, String>(); 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
CS-2852 Data Structures, Andrew J. Wozniewicz
Map Example: Map of Arraysimport java.util.Iterator;import java.util.Map;import java.util.TreeMap;
public class MapArray { public static void main(String[] args) { Map<String, int[]> map = new TreeMap<String, int[]>();
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...}
CS-2852 Data Structures, Andrew J. Wozniewicz
Map Example: Map of Arraysimport java.util.Iterator;import java.util.Map;import java.util.TreeMap;
public class MapArray {
// Code from previous slide goes here
Iterator<String> 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