Presentation is loading. Please wait.

Presentation is loading. Please wait.

© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered.

Similar presentations


Presentation on theme: "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered."— Presentation transcript:

1 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered Set and Map Implementation Bret Ford © 2005, Prentice Hall

2 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing the TreeSet Class TreeSet class is actually the STree class that implements the Set and OrderedSet interfaces. TreeSet class is actually the STree class that implements the Set and OrderedSet interfaces. Private static inner class STNode objects store data. Private static inner class STNode objects store data.

3 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. OrderedSet Interface Hierarchy

4 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeSet Class public class TreeSet implements OrderedSet { // reference to root of a search tree that is // the underlying storage structure for a // TreeSet collection private STNode root; // number of elements in the tree private int setSize; // increases whenever the tree changes; // used by an iterator to verify that it // is in a consistent state private int modCount;...

5 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeSet Class (concluded) // inner class that provides for // iterator operations private class IteratorImpl implements Iterator {... } // static inner class that defines STNode // objects which are the building blocks // of the binary search tree private static class STNode {... }

6 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview The TreeMap class implements the Map interface which defines methods like get(), put(), and remove() that access and update elements in a map collection. The TreeMap class implements the Map interface which defines methods like get(), put(), and remove() that access and update elements in a map collection. The Map interface specifies the interface Map.Entry as an inner interface that defines the structure of the key ‑ value pairs that are inserted into a map. The Map interface specifies the interface Map.Entry as an inner interface that defines the structure of the key ‑ value pairs that are inserted into a map.

7 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview (continued) In an entry set, a programmer can use a Map.Entry reference to access the key and value with the methods getKey() and getValue() and can update the value component using setValue(). No update to the key component is available since the operation could destroy the tree ordering of the map.

8 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview (continued) The OrderedMap interface defines methods that return minimum and maximum elements. The method firstKey() returns the first (least) key in the ordered map, and the method lastKey() returns the last (greatest) key in the map.

9 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview (continued) The UML diagram shows the relationship between the Map, Map.Entry and OrderedMap interfaces.

10 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview (continued) Implement a TreeMap as a binary search tree of Entry nodes, where Entry is a private static inner class. Each node has a key-value pair and references to its children and parent.

11 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Implementation Overview (concluded) The Entry objects in the search tree are ordered by the key. The figure illustrates a TreeMap with solid lines connecting a node to its children and a dotted line connecting a node to its parent.

12 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Entry as an Inner-Class Within TreeMap public class TreeMap implements OrderedMap {... // declares a binary search tree node object private static class Entry implements Map.Entry { // node data K key; V value; // child links and link to the node's parent Entry left, right, parent;

13 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Entry as an Inner-Class Within TreeMap (continued) // constructor that initializes the value // and parent fields and sets the link // fields left and right to null public Entry(K key, V value, Entry parent) { this.key = key; this.value = value; left = null; right = null; this.parent = parent; }

14 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Entry as an Inner-Class Within TreeMap (continued) // returns the key public K getKey() { return key; } // returns the value associated with the key public V getValue() { return value; }

15 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Entry as an Inner-Class Within TreeMap (concluded) // updates the value currently associated // with the key with a new one and returns // the original value public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } // used by TreeMap toString() to list the // pair as "key=value" public String toString() { return key + "=" + value; } }

16 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Class Design The TreeMap class builds a binary search tree of Entry objects. The TreeMap class builds a binary search tree of Entry objects. Variables Variables The private instance variable root is a reference to an Entry node that defines the search tree. The private instance variable root is a reference to an Entry node that defines the search tree. Two integer variables mapSize and modCount maintain the size of the collection and the number of tree modifications (insertions and deletions). Two integer variables mapSize and modCount maintain the size of the collection and the number of tree modifications (insertions and deletions).

17 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Class Design (continued) The class constructor creates an empty map and toString() displays the entries as comma-separated elements enclosed in braces ("{", "}"). Each element has the form "key=value". The class constructor creates an empty map and toString() displays the entries as comma-separated elements enclosed in braces ("{", "}"). Each element has the form "key=value". The other methods implement OrderedMap interface operations. The other methods implement OrderedMap interface operations.

18 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Class Design (continued) The figure shows a UML diagram illustrating the design of the TreeMap class. The inner classes IteratorImpl, KeyIterator, and EntryIterator are involved with the collection views of a map. The figure shows a UML diagram illustrating the design of the TreeMap class. The inner classes IteratorImpl, KeyIterator, and EntryIterator are involved with the collection views of a map.

19 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Class – Basic Class Structure public class TreeMap implements OrderedMap { // root defines the search tree of Entry nodes private Entry root; // size of the map private int mapSize; // modCount maintains a record of changes // to the map for iterators private int modCount;

20 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Class – Basic Class Structure (concluded) // constructor creates an empty map public TreeMap() { root = null; mapSize = 0; modCount = 0; }... // declares a binary search tree node object private static class Entry implements Map.Entry {... } }

21 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: getEntry() Map methods such as get(), containsKey(), and remove() use a key argument to access an entry in the map. Map methods such as get(), containsKey(), and remove() use a key argument to access an entry in the map. The private method getEntry() takes a key and searches the tree for a pair with the specified key. It returns a reference to the key-value pair in the tree or null of it failed to locate an entry with the key. The private method getEntry() takes a key and searches the tree for a pair with the specified key. It returns a reference to the key-value pair in the tree or null of it failed to locate an entry with the key.

22 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: getEntry() (continued) // iteratively traverse a path from the root // to the entry key; return a reference to the // node containing key or null if the search fails private Entry getEntry(K key) { // scan variable entry references the current // node in the traversal Entry entry = root; int orderValue; // terminate on an empty subtree while(entry != null) { // compare item and the current node // value based on the key orderValue = ((Comparable )key).compareTo( entry.key);

23 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: getEntry() (concluded) // if a match occurs, return true; // otherwise, go left or go right // following search tree order if (orderValue == 0) return entry; else if (orderValue < 0) entry = entry.left; else entry = entry.right; } return null; }

24 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: containsKey() The method containsKey() indicates whether an entry with the specified key is in the map. Its implementation is a direct application of getEntry(). The method containsKey() indicates whether an entry with the specified key is in the map. Its implementation is a direct application of getEntry().

25 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: containsKey() (concluded) // returns true if this map contains an entry // with the specified key public boolean containsKey(Object key) { return getEntry((K)key) != null; }

26 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: get() Access to the value component of a key- value pair is provided by the method get(). Access to the value component of a key- value pair is provided by the method get(). After calling getEntry() to locate the entry, the method returns null or the value field depending on whether the entry is in the map. After calling getEntry() to locate the entry, the method returns null or the value field depending on whether the entry is in the map.

27 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Key Access to an Entry: get() (concluded) // returns the value correponding to key public V get(K key) { Entry p = getEntry(key); if (p == null) return null; else return p.getValue(); }

28 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Updating an Entry: put() The put() operation with arguments for the key and the value either updates the value field for an existing entry or adds a new entry. The put() operation with arguments for the key and the value either updates the value field for an existing entry or adds a new entry. Start at the root and search down a path using search tree ordering. If a match occurs, use setValue() to update the value field in the matching entry. Start at the root and search down a path using search tree ordering. If a match occurs, use setValue() to update the value field in the matching entry. Otherwise,create an Entry object with the specified key and value arguments and add the new node. Otherwise,create an Entry object with the specified key and value arguments and add the new node.

29 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Updating an Entry: put() (continued) // associates the specified value with the // specified key in this map; returns the // previous value associated with the key, // or null if there was no mapping for key public V put(K key, V value) { // entry is current node in traversal, parent // the previous node Entry entry = root, parent = null, newNode; int orderValue = 0; // terminate on an empty subtree while(entry != null) { // update the parent reference parent = entry; // compare key to the current node key orderValue = ((Comparable )key).compareTo( entry.key);

30 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Updating an Entry: put() (continued) // if a match occurs, replace the value // in entry and return the previous value; // otherwise, go left or go right following // search tree order if (orderValue == 0) // return; put() is an update return entry.setValue(value); else if (orderValue < 0) entry = entry.left; else entry = entry.right; } // create the new node newNode = new Entry (key, value, parent);

31 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Updating an Entry: put() (concluded) if (parent == null) // this is the first node added; make it root root = newNode; else if (orderValue < 0) // attach newNode as the left child of parent parent.left = newNode; else // attach newNode as the right child of parent parent.right = newNode; // increment the tree size and modCount mapSize++; modCount++; // the return is the value of a matching entry; // returning null indicates we added a new pair // to the tree return null; }

32 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Removing an Entry: remove() Use getEntry() to determine if there is a key ‑ value pair in the map with the specified key. Use getEntry() to determine if there is a key ‑ value pair in the map with the specified key. If there is, the private method removeNode() takes a reference to the node and deletes it from the tree. The method removeNode() uses the deletion algorithm for a binary search tree. If there is, the private method removeNode() takes a reference to the node and deletes it from the tree. The method removeNode() uses the deletion algorithm for a binary search tree.

33 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Removing an Entry: remove() (concluded) // removes the entry containing key from // this map if present public V remove(Object key) { // search tree for key Entry dNode = getEntry((K)key); if (dNode == null) return null; V returnObj = dNode.getValue(); removeNode(dNode); mapSize--; modCount++; return returnObj; }

34 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. A Collection View A collection view object does not have its own data. It uses the data in the backing collection. A collection view object does not have its own data. It uses the data in the backing collection. A view object has operations that are tied to operations in the backing collection. In the case of a keySet collection view for a map, the operations implement the Set interface but the add() operation is disallowed. The data are the keys of the entries in the backing map. A view object has operations that are tied to operations in the backing collection. In the case of a keySet collection view for a map, the operations implement the Set interface but the add() operation is disallowed. The data are the keys of the entries in the backing map.

35 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. StoreOneTwo Class Class StoreOneTwo Class StoreOneTwo Variables one and two that hold integer values. Variables one and two that hold integer values. A constructor that initializes the values. A constructor that initializes the values. toString() that provides a representation of the object in the form "one=two". toString() that provides a representation of the object in the form "one=two". Method setOneTwo() that allows the programmer to update the variables. Method setOneTwo() that allows the programmer to update the variables.

36 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. View Interface Associated with the class StoreOneTwo create an interface called View defining methods get() and set() that may be used by a View object to access and update a field in the backing object. Associated with the class StoreOneTwo create an interface called View defining methods get() and set() that may be used by a View object to access and update a field in the backing object.

37 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. View interface (concluded) // an object that implements View has // methods to access and update a data // item in a backing object public interface View { int get(); void set(int value); }

38 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. StoreOneTwo Class (continued) The StoreOneTwo class defines the method viewOne() which returns a View object that is associated with field one in a StoreOneTwo object. The StoreOneTwo class defines the method viewOne() which returns a View object that is associated with field one in a StoreOneTwo object.

39 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. StoreOneTwo Class Declaration public class StoreOneTwo { // object has two integer fields private int one, two; // constructor; initialize data fields public StoreOneTwo(int one, int two) { this.one = one; this.two = two; } // return a representation of the object public String toString() { return one + "=" + two; }

40 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. StoreOneTwo Class Declaration (concluded) // update the data fields public void setOneTwo(int one, int two) { this.one = one; this.two = two; } // object that is returned by viewOne() private View viewObj = null; // method returns a View object // associated with field one public View viewOne() {... } }

41 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example using viewOne() // create object and display its current values StoreOneTwo st = new StoreOneTwo(5, 35); // use the View object to access the first field in st View v = st.view();

42 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Example using viewOne() (concluded) System.out.println("Initial object st: " + st); System.out.println("Value viewed from st = " + v.get()); // use view object v to update the first field in st v.set(25); System.out.println("Updated object st: " + st); // use setOneTwo() to update the object directly the // display the view of the object using v.get() st.setOneTwo(3, 7); System.out.println("Value viewed from updated st: " + v.get()); Output: Initial object st: 5=35 Value viewed from st = 5 Updated object st: 25=35 Value viewed from updated st: 3

43 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing a View In the StoreOneTwo class, the method viewOne() returns an object that implements the View interface. The object does not have its own data; rather, it relies on access to the variable one in a StoreOneTwo object. In the StoreOneTwo class, the method viewOne() returns an object that implements the View interface. The object does not have its own data; rather, it relies on access to the variable one in a StoreOneTwo object.

44 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing a View (continued) A view is usually implemented using an anonymous inner class. Such a class does not have a name. An anonymous inner class combines the declaration of an inner class with the creation of an instance of the class in one step, e.g. A view is usually implemented using an anonymous inner class. Such a class does not have a name. An anonymous inner class combines the declaration of an inner class with the creation of an instance of the class in one step, e.g. // object that is returned by viewOne() private View viewObj = null;... // creates instance of class that implements View viewObj = new View() { <implementation of the methods get() and set() which access the variable one in the outer class> }

45 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing a View (continued) // object that is returned by viewOne() private View viewObj = null; // method returns a View object that // accesses the StoreOneTwo field one public View viewOne() { // we only generate one instance of the // anonymous inner class object if (viewObj == null) viewObj = new View() { // methods in the View interface public int get() { return one; } public void set(int value) { one = value; } };

46 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementing a View (concluded) // return the object created by // the method viewOne() return viewObj; }

47 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. The keySet Collection View The TreeMap class implements its keySet and entrySet views by returning an anonymous inner class object that implements the Set interface and uses the map data. The TreeMap class implements its keySet and entrySet views by returning an anonymous inner class object that implements the Set interface and uses the map data.

48 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. keySet() Outline private Set keySet = null; public Set keySet() { if (keySet == null) { keySet = new Set () { public Iterator iterator() {... } public int size() {... } public boolean contains(Object item) {... } public boolean remove(Object item) {... }

49 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. keySet() Outline (concluded) public void clear() {... } public boolean isEmpty() {... } public boolean add(K key) { throw new UnsupportedOperationException(); } }; } return keySet; }

50 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Implementation of keySet() methods The Set methods size(), isEmpty(), and clear() have implementations that use the corresponding TreeMap methods. The Set methods size(), isEmpty(), and clear() have implementations that use the corresponding TreeMap methods. To reference "this" for the enclosing class, preface it by the name of the enclosing class followed by the "." operator. For instance, TreeMap.this.size() refers to the method size() in the TreeMap class. To reference "this" for the enclosing class, preface it by the name of the enclosing class followed by the "." operator. For instance, TreeMap.this.size() refers to the method size() in the TreeMap class.

51 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. keySet Collection view size() // access size in the backing map public int size() { return TreeMap.this.size(); }

52 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. keySet Collection view contains() // use containsKey() to check if the entry // with item as its key is in the map public boolean contains(Object item) { return containsKey(item); }

53 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. keySet Collection view add() The Set method add() must be implemented. The object would become a key without any associated value. Throw an UnsupportedOperationException which has the effect of making the operation invalid. The Set method add() must be implemented. The object would become a key without any associated value. Throw an UnsupportedOperationException which has the effect of making the operation invalid. public boolean add(K key) { throw new UnsupportedOperationException(); }

54 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Iterators The keySet and the entrySet collection views provide an iterator that scans the keys in the map. The keySet and the entrySet collection views provide an iterator that scans the keys in the map. In the implementation of keySet(), the method iterator() returns an Iterator object of type KeyIterator. In the implementation of keySet(), the method iterator() returns an Iterator object of type KeyIterator. In the implementation of entrySet(), the return Iterator object is of type EntryIterator. In the implementation of entrySet(), the return Iterator object is of type EntryIterator. Both of these Iterator classes must implement next(), hasNext(), and remove(). Both of these Iterator classes must implement next(), hasNext(), and remove().

55 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Iterators (continued) Simply the task by creating a generic class IteratorImpl that sequences through the key ‑ value pairs in the map and implements all the iterator methods except next(). Simply the task by creating a generic class IteratorImpl that sequences through the key ‑ value pairs in the map and implements all the iterator methods except next(). The inner class KeyIterator is a subclass of the inner class IteratorImpl with generic type K. It adds an implementation for next() that returns the next key in the map. The inner class KeyIterator is a subclass of the inner class IteratorImpl with generic type K. It adds an implementation for next() that returns the next key in the map.

56 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Iterators (continued) private class KeyIterator extends IteratorImpl { public K next() {... } }

57 © 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. TreeMap Iterators (concluded) The inner class EntryIterator is a subclass of the inner class IteratorImpl with generic type Map.Entry. This class adds an implementation for next() that returns the next key-value pair (Entry) in the map The inner class EntryIterator is a subclass of the inner class IteratorImpl with generic type Map.Entry. This class adds an implementation for next() that returns the next key-value pair (Entry) in the map private class EntryIterator extends IteratorImpl > { public K next() {... } }


Download ppt "© 2005 Pearson Education, Inc., Upper Saddle River, NJ. All rights reserved. Data Structures for Java William H. Ford William R. Topp Chapter 20 Ordered."

Similar presentations


Ads by Google