Data Structures TreeMap HashMap.

Slides:



Advertisements
Similar presentations
Chapter 7. Binary Search Trees
Advertisements

1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
Binary Trees. DCS – SWC 2 Binary Trees Sets and Maps in Java are also available in tree-based implementations A Tree is – in this context – a data structure.
Binary Trees, Binary Search Trees CMPS 2133 Spring 2008.
Sets and Maps Chapter 9. Chapter 9: Sets and Maps2 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn about.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved L15 (Chapter 22) Java Collections.
1 abstract containers hierarchical (1 to many) graph (many to many) first ith last sequence/linear (1 to 1) set.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
Binary Search Trees. BST Properties Have all properties of binary tree Items in left subtree are smaller than items in any node Items in right subtree.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
1 Trees Tree nomenclature Implementation strategies Traversals –Depth-first –Breadth-first Implementing binary search trees.
AITI Lecture 20 Trees, Binary Search Trees Adapted from MIT Course 1.00 Spring 2003 Lecture 28 and Tutorial Note 10 (Teachers: Please do not erase the.
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
Big Java Chapter 16.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Chapter 18 Java Collections Framework
Sets, Maps and Hash Tables. RHS – SOC 2 Sets We have learned that different data struc- tures have different advantages – and drawbacks Choosing the proper.
Sets and Maps Chris Nevison. Set Interface Models collection with no repetitions subinterface of Collection –has all collection methods has a subinterface.
Building Java Programs Bonus Slides Hashing. 2 Recall: ADTs (11.1) abstract data type (ADT): A specification of a collection of data and the operations.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
Collections Mrs. C. Furman April 21, Collection Classes ArrayList and LinkedList implements List HashSet implements Set TreeSet implements SortedSet.
Week 10 - Friday.  What did we talk about last time?  Graph representations  Adjacency matrix  Adjacency lists  Depth first search.
Week 9 - Friday.  What did we talk about last time?  Collisions  Open addressing ▪ Linear probing ▪ Quadratic probing ▪ Double hashing  Chaining.
Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 21 Sets and Maps.
Sets and Maps Chapter 9. Chapter Objectives  To understand the Java Map and Set interfaces and how to use them  To learn about hash coding and its use.
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
Chapter 21 Sets and Maps Jung Soo (Sue) Lim Cal State LA.
CS422 Principles of Database Systems Indexes
Sets and Maps Chapter 9.
Slides by Donald W. Smith
11 Map ADTs Map concepts. Map applications.
CSCE 3110 Data Structures & Algorithm Analysis
CSCE 3110 Data Structures & Algorithm Analysis
Chapter 19 Java Data Structures
Efficiency of in Binary Trees
Binary Search Tree (BST)
Lecture 22 Binary Search Trees Chapter 10 of textbook
Week 11 - Friday CS221.
abstract containers sequence/linear (1 to 1) hierarchical (1 to many)
COMP 103 Binary Search Trees.
ITEC 2620M Introduction to Data Structures
i206: Lecture 13: Recursion, continued Trees
Binary Trees.
Binary Search Trees.
Map interface Empty() - return true if the map is empty; else return false Size() - return the number of elements in the map Find(key) - if there is an.
Road Map CS Concepts Data Structures Java Language Java Collections
TreeSet TreeMap HashMap
CSE 373: Data Structures and Algorithms
Find in a linked list? first last 7  4  3  8 NULL
slides created by Marty Stepp and Hélène Martin
CSE 373: Data Structures and Algorithms
Sets, Maps and Hash Tables
slides adapted from Marty Stepp and Hélène Martin
CSE 373 Data Structures and Algorithms
Lecture 12 CS203 1.
Exercise Write a program that counts the number of unique words in a large text file (say, Moby Dick or the King James Bible). Store the words in a collection.
Chapter 10 1 – Binary Trees Tree Structures (3 slides)
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
Sets and Maps Chapter 9.
slides created by Marty Stepp
Podcast Ch21f Title: HashSet Class
slides created by Marty Stepp and Hélène Martin
Data Structures II AP Computer Science
CO4301 – Advanced Games Development Week 12 Using Trees
Tree (new ADT) Terminology: A tree is a collection of elements (nodes)
Presentation transcript:

Data Structures TreeMap HashMap

Review of Binary Trees All nodes to the left are smaller than the parent. All nodes to the right are larger than the parent. Each node is unique. No duplicates. A balanced binary tree has 2(k+1)-1 nodes. The maximum number of comparisons required to locate a given node is k.

Why are Binary Search Trees (BST) Important? Binary search trees are used to store large amounts of data They have a high capacity – Approximately 2k. They have fast search access (k comparisons). Basic tree operations (insert, find, delete) are fairly simple to implement. TIPS: It is important to keep the tree balanced, so that all branches are comparable length. This may require sophistication. Java has a Tree implementation.

Java Tree API A Tree is a non-linear data structure. The Tree data structure is useful on occasions where linear representation is not a good option. Java provides two in-built classes, TreeSet and TreeMap, in Collection Framework.

Java TreeSet and TreeMap TreeSet represents a collection of distinct elements. TreeMap represents a collection of elements as a key, value pair. Each key maps to one value only; that means it disallows duplicate keys. A value with a distinct key may be duplicated, however.

Exercise 1: Use the TreeSet to Construct a Binary Search Tree Instantiate an empty binary search tree object named bst. Insert the following nodes: “b”, “q”, “t”, “d”, “a” The first node, “b”, will be the root. Draw the tree by hand and perform an inOrder, postOrder, and preOrder traversal. Display each node in bst. TIP: Use the toArray() method to create an array holding all the nodes. Question: What type of traversal was used in toArray()?

Java Tree Implementation Trees are efficient if they are balanced. A balanced tree of depth 20 can hold about 220 nodes. If the tree were unbalanced, in the worst case it would require k levels to hold k nodes and k steps to locate, insert, and delete a node TIP: To prevent unbalanced, Java uses a binary tree known as a red-black tree. Red-black trees automatically rebalance themselves if one branch becomes deeper than a sibling.

Exercise 2 Part I: Build FullName class implemented as a Comparable Comparable is an interface that imposes an ordering on objects of the class that implements it. This ordering is a natural ordering. The class's compareTo() method is referred to as its natural comparison method. This method will compare this object with a specified object for order and will return one of -1, 0, or 1. -1: this object was less than the specified object. 0 : this object was equal to the specified object. 1: this object was greater than the specified object.

public class FullName implements Comparable<FullName> { private final String firstName; private final String lastName; public FullName(String f, String l) { firstName = f; lastName = l; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int compareTo(FullName fn) { // Complete the compareTo() method. Order by last name, then first name. // NOTE: String has a compareTo() method public String toString() { // Complete the toString() method. Return first name, a space, and last name.

Exercise 2 Part II: Create a TreeSet object to store a tree of names FullName f1 = new FullName("Manuel", ”Nader"); FullName f2 = new FullName("Kacey", ”Que"); FullName f3 = new FullName("Jason", "Red"); FullName f4 = new FullName("Bobo", ”Baca"); TreeSet<FullName> names = new TreeSet<FullName>(); names.add(f1); names.add(f2); names.add(f3); names.add(f4);

Exercise 2 Part III: Display the tree of names. for (FullName f : names) System.out.println(f); Question: What order of traversal was used in accessing names?

TreeMap Each node in a TreeMap contains a key and a value. A “key” is an ordered value, i.e. a key can be compared with another object of the same type. A node in an ordered TreeMap consists of an ordered key and a value. All the keys in a TreeMap should be of the samne type.

Exercise 3 Part I: Create a phonebook (TreeMap) with the following entries. Indicate the in-order traversal. What is the key in the code below? What is the value in the code below? TreeMap<FullName,String> phones= new TreeMap<FullName,String>(); FullName f1 = new FullName("Manuel", ”Nader"); phones.put(f1, "639-2287");

Exercise 3 Part II: Answers to questions In the phones TreeMap, what is the node key? FullName is the key. In the phones TreeMap, what is the value? String (phone number) is the value.

Exercise 3 Part III: Create a TreeSet object to store a tree of names Use a loop to display a JOptionPane that asks for a full name in the format: “firstName lastName”. Create a lookup method that searches for and displays the phone number for the input name. TIPS: Use the String method split() to parse the name. -split() takes the delimiter as its argument and returns an array of Strings. Use the TreeMap<FullName, String> method get() to return the phone number of the entered person. -get() will return the value if the key is found and a null if the key cannot be found.

Exercise 3 Part III Code Guide while (true) { String text= JOptionPane.showInputDialog("Enter full name"); if (text.isEmpty()) break;   // TASK 1: Parse the full name (firstName lastName) // TASK 2: Use  get()  with FullName key to retrieve phone number value. // TASK 3:Print the phone number or "Subscriber unknown" if get() returns a null }

Can we do better than a TreeMap for Data Structure Efficiency? Possibly. What about a HashMap?

Hashing Illustration Keys = {a, b, c, d, aa, cc, dd} Hash Function: (sum of chars) % 4 Hashing maps each Object to an index in an array of Node references. The array contains the “first reference to a linked list of Objects. We traverse the list to add or find Objects that hash to that value. We keep the lists short, so hash efficiency is close to array index lookup.

A Closer look at HashMap HashMap holds keys and values, similar to TreeMap HashMap is similar to a filing cabinet, in which each folder has a tab (hash code) and contains a small number of objects (list) HashMap can provide a quick lookup time. This time depends on having a good hashCode() method and is statistical. Elements in a HashMap are NOT ordered by anything useful. Storage order is by hash code.

Java Map API 1. Instantiate a HashMap: Map<String, String> map = new HashMap<String, String>(); 2. Store a key/value pair in the map: map.put(key, value); 3. Retrieve a stored value for a key, or null if that key is not present in the map map.get(key) . map.get(key) 4. Determine if a key is in the map: map.containsKey(key) 5. Remove the key/value pair, if the key is present. map.remove(key)

Exercise 4: Use HashMap to Construct the phone book TASK 1: Add an equals() method to the FullName class. The equals method implements an equivalence relation between (non null) object references. The Object class already provides an implementation of the equals method. Add an Override. @Override public boolean equals(Object obj) {               }

Solution : equals() @Override     public boolean equals(Object obj) {         boolean equalObjects = false;               //NOTE: getClass() returns the runtime class of a given Object.         if (obj != null && this.getClass() == obj.getClass()) {             FullName fnObj = (FullName) obj;             equalObjects =                 firstName.equals(fnObj.getFirstName()) &&                 lastName.equals(fnObj.getLastName());         }         return equalObjects;     }

Exercise 4: Use HashMap to Construct the phone book TASK 2: Add a hashCode() method to the FullName class. Use the pattern from a previous slide : Hash Function: (sum of chars) % 4

hashCode() @Override public int hashCode() {         return (firstName.length() + lastName.length()) % 4;     }

Exercise 4: Use HashMap to Construct the phone book TASK 3: Search for a phone number using a HashMap

Final Points The TreeSet and TreeMap classes are the most obvious implementation of binary tree data structure in the Java API Library. For the high-level users, the rules of data organization do not make any difference in its usages. The tree structure is slightly more complicated and inefficient than its non-tree or linear counterparts, like HashMap, due to the numerous rules to maintain the norms of a balanced tree structure. Unless a specific need arises, its HashMap should be used more often than trees.