Copyright © 2002, Systems and Computer Engineering, Carleton University. 94.204-08-Hashtable.ppt 1 94.204* Object-Oriented Software Development Unit 8.

Slides:



Advertisements
Similar presentations
Sequence of characters Generalized form Expresses Pattern of strings in a Generalized notation.
Advertisements

Hashing as a Dictionary Implementation
© 2004 Goodrich, Tamassia Hash Tables1  
Maps. Hash Tables. Dictionaries. 2 CPSC 3200 University of Tennessee at Chattanooga – Summer 2013 © 2010 Goodrich, Tamassia.
The Symbol Table Lecture 13 Wed, Feb 23, The Symbol Table When identifiers are found, they will be entered into a symbol table, which will hold.
Fall 2007CS 225 Sets and Maps Chapter 9. Fall 2007CS 225 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn.
1 Chapter 9 Maps and Dictionaries. 2 A basic problem We have to store some records and perform the following: add new record add new record delete record.
Using Maps. A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
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.
hashing1 Hashing It’s not just for breakfast anymore!
Hash Tables1 Part E Hash Tables  
Hash Tables1 Part E Hash Tables  
1 Java Object Model Part 2: the Object class. 2 Object class Superclass for all Java classes Any class without explicit extends clause is a direct subclass.
Dictionaries and Hash Tables Cmput Lecture 24 Department of Computing Science University of Alberta ©Duane Szafron 2000 Some code in this lecture.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Dictionaries 4/17/2017 3:23 PM Hash Tables  
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
The Collections Framework A Brief Introduction. Collections A collection is a structured group of objects –An array is a kind of collection –A Vector.
Using Maps. 2 A simple map: Hashtable To create a Hashtable, use: import java.util.*; Hashtable table = new Hashtable(); To put things into a Hashtable,
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.
CS2110 Recitation Week 8. Hashing Hashing: An implementation of a set. It provides O(1) expected time for set operations Set operations Make the set empty.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
Hash Functions and the HashMap Class A Brief Overview On Green Marble John W. Benning.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
Jan 12, 2012 Introduction to Collections. 2 Collections A collection is a structured group of objects Java 1.2 introduced the Collections Framework Collections.
Copyright © 2002, Systems and Computer Engineering, Carleton University Patterns.ppt * Object-Oriented Software Development Part 11.
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.
1 Concrete collections II. 2 HashSet hash codes are used to organize elements in the collections, calculated from the state of an object –hash codes are.
Hash Tables1   © 2010 Goodrich, Tamassia.
Data structures Abstract data types Java classes for Data structures and ADTs.
1/20/03A2-1 CS494 Interfaces and Collection in Java.
CSE 501N Fall ‘09 11: Data Structures: Stacks, Queues, and Maps Nick Leidenfrost October 6, 2009.
3-February-2003cse Collections © 2003 University of Washington1 Java Collections CSE 403, Winter 2003 Software Engineering
Hashing Hashing is another method for sorting and searching data.
© 2004 Goodrich, Tamassia Hash Tables1  
Hashing as a Dictionary Implementation Chapter 19.
Chapter 12 Hash Table. ● So far, the best worst-case time for searching is O(log n). ● Hash tables  average search time of O(1).  worst case search.
Author: Takdir, S.ST. © Sekolah Tinggi Ilmu Statistik.
Chapter 11 Hash Anshuman Razdan Div of Computing Studies
Sets and Maps Computer Science 4 Mr. Gerb Reference: Objective: Understand the two basic applications of searching.
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.
A Introduction to Computing II Lecture 11: Hashtables Fall Session 2000.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Copyright (c) Systems and Computer Engineering, Carleton University * Object-Oriented Software Development Unit 13 The Collections Framework.
Hashing O(1) data access (almost) -access, insertion, deletion, updating in constant time (on average) but at a price… references: Weiss, Goodrich & Tamassia,
Java Methods A & AB Object-Oriented Programming and Data Structures Maria Litvin ● Gary Litvin Copyright © 2006 by Maria Litvin, Gary Litvin, and Skylight.
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.
Collections Dwight Deugo Nesa Matic
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
The Object class Object package java.lang Object clone equals hashCode toString aCopy toThis hash string ! yesOrNo.
CSE 143 Lecture 11: Sets and Maps reading:
Hashing By Emily Nelson. The Official Definition Using a hash function to turn some kind of data in relatively small integers or Strings The “hash code”
Building Java Programs Generics, hashing reading: 18.1.
Sets and Maps Chapter 9.
Hash Tables 3/25/15 Presentation for use with the textbook Data Structures and Algorithms in Java, 6th edition, by M. T. Goodrich, R. Tamassia, and M.
Searching.
CS313D: Advanced Programming Language
Hashing as a Dictionary Implementation
CSE 373: Data Structures and Algorithms
L5. Necessary Java Programming Techniques
Sets and Maps Chapter 9.
Hashing in java.util
CS210- Lecture 16 July 11, 2005 Agenda Maps and Dictionaries Map ADT
Presentation transcript:

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt * Object-Oriented Software Development Unit 8 Hashtables (Case Study of Using and Overriding Methods Inherited from Class Object) revised January 2002

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 2 Class Object Comparing, copying and printing are just three of the behaviours defined in the class Object. There are other behaviours that only become apparent as your programming experience broadens. Example : public native int hashCode(); –We must first introduce hashtables, then discuss how we should override hashCode() from class Object.

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 3 Tables A table is a collection of pairs of items (key, value) When you put a value in the table, you associate the value with a key To retrieve a value from the table, you provide a key, and the table looks up and returns the value associated with the key

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 4 Example An FGR posted outside the Registrar’s office: Student # Grade B+ A+ B- values keys

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 5 Example A departmental telephone directory Name Ext. Homer Marge Lisa values keys

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 6 Java's Hashtable Class The Java API provides class Hashtable in package java.util –(note the lower-case "t". Yes, this is inconsistent with the normal Java naming conventions.) public class Hashtable extends Dictionary

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 7 Suppose we want to keep a table of employee records –each employee has an ID number, which will be used as the key Employee engineer = new Employee(); engineer.setID( "98765“ ); Question : Employee ID is the key AND part of the value. Why don’t we just use a list of Employee objects? Employee IDEmployee Example :Employee id=98765 …

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 8 Java.util.Hashtable Constructors public Hashtable(); public Hashtable (int initialCapacity, float loadFactor); public Hashtable (int initialCapacity); In our example : Hashtable staff = new Hashtable(); // According to JBuilder, // a default capacity=101

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 9 java.util.Hashtable put() public Object put (Object key, Object value) put() associates a value (any object) with a key (an object), and stores the value in the hash table –later, we will discuss how to design a class so that its instances can be used as keys

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 10 java.util.Hashtable put() Keys must be unique –You cannot store two values with the same key. If you call put() twice with the same key, the second value replaces the first value –put() uses the equals() method of the key object to compare –put() returns the previous value stored with that key. If put() returns a non-null value, you know that you have replaced a previous entry

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 11 java.util.Hashtable put() In our example : String id = engineer.getID(); Object old = staff.put( id, engineer ); if (old != null) { // id over-wrote oldID String oldId = (String)old; … } // or simply: if (staff.put( engineer.getID(), engineer ) != null) {…

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 12 java.util.Hashtable get() public Object get(Object key) get() returns the value associated with the specified key, and leaves the value in the table –get() returns null if the table does not contain a value associated with the specified key To retrieve information about an employee, we need to know the key (the employee ID): String s = "98765"; Object o = staff.get( s ); if ((o != null) && (o instanceof Employee)) { Employee e = (Employee)o;

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 13 java.util.Hashtable Search Methods public boolean contains ( Object value) contains() returns true if the hash table contains the specified value Employee e2 = new Employee(…); if ( staff.contains( e2 ) { … } // Uses Employee#equals() to compare e2 // to all employee records stored in the // table

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 14 java.util.Hashtable Search Methods public boolean containsKey ( Object key ) containsKey() returns true if the hash table contains the specified key if ( staff.containsKey( “98765”) ) { … } // Uses String#equals() to compare // “98765” to all keys used in the table.

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 15 More java.util.Hashtable methods public Object remove(Object key) Deletes a key/value association from the table public void clear(); Clears table so it has no keys public int size(); Returns the number of entries in the table public boolean isEmpty(); Returns true if the table is empty And the methods inherited from Class Object: public boolean equals(Object o) public String toString(); public Object clone();

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 16 More java.util.Hashtable Methods Tables are not “ordered” like lists. We cannot index through the elements. for (i=0;i<staff.size();i++) Employee e=(Employee)staff.get(i) public Enumeration keys(); public Enumeration elements (); Return Enumeration objects to allow you to iterate through the complete set of keys or values stored in a table We will discuss enumerations (or iterators) later, but a quick example is given Enumeration e = staff.elements(); while (e.hasMoreElements() ) {Employee e = (Employee)e.nextElement();} Can’t do this

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 17 Hash Table Theory Consider how we could implement the FGR or dept. phone list tables If we used an array or linked list to store key/value pairs, retrieving a value would require a sequential search through the keys –for large tables, this is inefficient

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 18 Hash Table Theory Think of a hash table as an array of “buckets” When we pass a key object to a hash table object, the table asks the key to compute its hash code public native int hashCode(); The hash code is used as the index into the array (it selects one bucket), and the key/value pair is stored in the bucket

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 19 Storing Key/Value Pairs in a java.util.Hashtable Object e.g., add key/value objects k1/v1 to the hash table: ht.put(k1, v1); k1.hashCode() == 1 k1 v1 ht

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 20 Storing Key/Value Pairs in a java.util.Hashtable Object e.g., add key/value objects k2/v2 to the hash table: ht.put(k2, v2); k2.hashCode() == 3 k1 v1 k2 v2 ht

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 21 Storing Key/Value Pairs in a java.util.Hashtable Object e.g., add key/value objects k1/v3 to the hash table: ht.put(k1, v3); k1.hashCode() == 1 k1 v3 k2 v2 ht replaces k1/v1

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 22 Hash Table Theory: Collisions What if two different key objects compute the same hash code? We say that there is a collision (multiple key/value pairs should be stored in the same bucket) This can be handled several ways, but a common approach is “chain” all key/value pairs with the same hashcode (i.e., the bucket is a linked list of key/value pairs)

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 23 Storing Key/Value Pairs in a Hashtable Object e.g., add key/value objects k3/v4 to the hash table: ht.put(k3, v4); k3.hashCode() == 1 k1 v3 k2 v2 ht k3 v4

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 24 Retrieving Values From a Hashtable Object ht.get(k1); returns v3 ht.get(k2); returns v2 ht.get(k3); returns v4 ht.get(k4); returns null –no such key in the hash table Facilities for minimizing collisions : protected void rehash(); –Resizes & re-organizes the hashtable The Load Factor A measure of “how full” the table is. Default = 0.75 Set as argument in constructor Rehash() is automatically called when this threshold is reached

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 25 Retrieving Values From a Hashtable Object Value retrieval is efficient –get() asks the key that is passed to it to compute its hash code –if the table contains a value associated with that key, it must be in the bucket that is selected by the hash code –get() has to search at most one bucket (list) for the specified key

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 26 What Objects Can Be Used As Keys? If a class overrides equals() and hashCode() as appropriate for the class, instances of the class can be used as keys in a Hashtable public native int hashCode() Extract from the javadoc page for Object: –“Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.”

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 27 hashCode() “The general contract of hashCode is: –Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer. This integer need not remain consistent from one execution of an application to another execution of the same application. –If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.”

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 28 Using Strings as Keys Why did our employee example work ? –If you look at the javadoc page for class String, you’ll see that it overrides hashCode() and equals()

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 29 Designing hashCode() If you want to use instances of one of your classes as keys in a hashtable, that class will have to provide a hashCode() method. Approach 1: Write your own hashCode() method –study the theory that underlies designing a good hashing function and write the method from scratch (not that difficult to do, but beyond the scope of this course)

Copyright © 2002, Systems and Computer Engineering, Carleton University Hashtable.ppt 30 Designing hashCode() Approach 2: Delegation –if your class has an association or aggregation relationship with an object that implements hashCode(), forward the hashCode() message to it, and use the value returned by the object; e.g., class SomeClass { HashableClass o;... public int hashCode() { // return o’s hash code as mine return o.hashCode(); } … }