Building Java Programs Generics, hashing reading: 18.1.

Slides:



Advertisements
Similar presentations
Hash Tables and Sets Lecture 3. Sets A set is simply a collection of elements Unlike lists, elements are not ordered Very abstract, general concept with.
Advertisements

CSE 1302 Lecture 23 Hashing and Hash Tables Richard Gesick.
Hashing as a Dictionary Implementation
Appendix I Hashing. Chapter Scope Hashing, conceptually Using hashes to solve problems Hash implementations Java Foundations, 3rd Edition, Lewis/DePasquale/Chase21.
CSE 143 Lecture 22: Advanced List Implementation (ADTs; interfaces; abstract classes; inner classes; generics; iterators)
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.
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.
1 CSE 326: Data Structures Hash Tables Autumn 2007 Lecture 14.
Hash Tables1 Part E Hash Tables  
Fall 2007CS 225 Sets and Maps Chapter 7. Fall 2007CS 225 Chapter Objectives To understand the Java Map and Set interfaces and how to use them To learn.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Introducing Hashing Chapter 21 Copyright ©2012 by Pearson Education, Inc. All rights reserved.
Hash Tables. Container of elements where each element has an associated key Each key is mapped to a value that determines the table cell where element.
Hash Tables. Container of elements where each element has an associated key Each key is mapped to a value that determines the table cell where element.
Hashing. Hashing as a Data Structure Performs operations in O(c) –Insert –Delete –Find Is not suitable for –FindMin –FindMax –Sort or output as sorted.
Hashing The Magic Container. Interface Main methods: –Void Put(Object) –Object Get(Object) … returns null if not i –… Remove(Object) Goal: methods are.
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:
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.
DATA STRUCTURES AND ALGORITHMS Lecture Notes 7 Prepared by İnanç TAHRALI.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
Hashing Hashing is another method for sorting and searching data.
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
Hashing as a Dictionary Implementation Chapter 19.
The Map ADT and Hash Tables. 2 The Map ADT  Map: An abstract data type where a value is "mapped" to a unique key  Need a key and a value to insert new.
CSC 427: Data Structures and Algorithm Analysis
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.
WEEK 1 Hashing CE222 Dr. Senem Kumova Metin
Chapter 11 Hash Anshuman Razdan Div of Computing Studies
1 CSC 427: Data Structures and Algorithm Analysis Fall 2011 Space vs. time  space/time tradeoffs  hashing  hash table, hash function  linear probing.
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.
H ASH TABLES. H ASHING Key indexed arrays had perfect search performance O(1) But required a dense range of index values Otherwise memory is wasted Hashing.
Hashtables. An Abstract data type that supports the following operations: –Insert –Find –Remove Search trees can be used for the same operations but require.
Hash Tables © Rick Mercer.  Outline  Discuss what a hash method does  translates a string key into an integer  Discuss a few strategies for implementing.
Chapter 13 C Advanced Implementations of Tables – Hash Tables.
1 CSE 331 Hash codes; annotations slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Week 15 – Wednesday.  What did we talk about last time?  Review up to Exam 1.
1 Data Structures CSCI 132, Spring 2014 Lecture 33 Hash Tables.
CMSC 341 Hashing Readings: Chapter 5. Announcements Midterm II on Nov 7 Review out Oct 29 HW 5 due Thursday CMSC 341 Hashing 2.
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.
Implementing the Map ADT.  The Map ADT  Implementation with Java Generics  A Hash Function  translation of a string key into an integer  Consider.
Sets and Maps Chapter 9.
Sections 10.5 – 10.6 Hashing.
Efficiency add remove find unsorted array O(1) O(n) sorted array
Hash Tables.
Hash tables Hash table: a list of some fixed size, that positions elements according to an algorithm called a hash function … hash function h(element)
Hashing CS2110 Spring 2018.
Building Java Programs
Hashing CS2110.
Lecture 26: Advanced List Implementation
slides created by Marty Stepp and Hélène Martin
CSE 373: Data Structures and Algorithms
slides adapted from Marty Stepp and Hélène Martin
CSE 373 Data Structures and Algorithms
CSE 373: Data Structures and Algorithms
CSE 373 Hash set implementation, continued
CSE 143 Lecture 25 Set ADT implementation; hashing read 11.2
CSE 143 Lecture 25 Advanced collection classes
Sets and Maps Chapter 9.
CSE 373 Separate chaining; hash codes; hash maps
slides created by Marty Stepp
Building Java Programs
Hashing based on slides by Marty Stepp
slides created by Marty Stepp and Hélène Martin
CSE 143 Lecture 21 Advanced List Implementation
CSE 373 Set implementation; intro to hashing
Sets and Maps Chapter 7 CS 225.
Presentation transcript:

Building Java Programs Generics, hashing reading: 18.1

2 Making hash browns... (We're talking about hashing. It makes sense.)

3 Hashing hash: To map a value to an integer index. hash table: An array that stores elements via hashing. hash function: An algorithm that maps values to indexes. one possible hash function for integers: HF(I)  I % length set.add(11);// 11 % 10 == 1 set.add(49);// 49 % 10 == 9 set.add(24);// 24 % 10 == 4 set.add(7);// 7 % 10 == 7 index value

4 Efficiency of hashing public static int hashFunction(int i) { return Math.abs(i) % elementData.length; } Add: set elementData[HF(i)] = i; Search: check if elementData[HF(i)] == i Remove: set elementData[HF(i)] = 0; What is the runtime of add, contains, and remove ? O(1) Are there any problems with this approach?

5 Hash Functions Maps a key to a number result should be constrained to some range passing in the same key should always give the same result Keys should be distributed over a range very bad if everything hashes to 1! should "look random" How would we write a hash function for String objects?

6 Hashing objects It is easy to hash an integer I (use index I % length ). How can we hash other types of values (such as objects)? All Java objects contain the following method: public int hashCode() Returns an integer hash code for this object. We can call hashCode on any object to find its preferred index. How is hashCode implemented? Depends on the type of object and its state. Example: a String's hashCode adds the ASCII values of its letters. You can write your own hashCode methods in classes you write. All classes come with a default version based on memory address.

7 Hash function for objects public static int hashFunction(E e) { return Math.abs(e.hashCode()) % elements.length; } Add: set elements[HF(o)] = o; Search: check if elements[HF(o)].equals(o) Remove: set elements[HF(o)] = null;

8 String's hashCode The hashCode function inside String objects looks like this: public int hashCode() { int hash = 0; for (int i = 0; i < this.length(); i++) { hash = 31 * hash + this.charAt(i); } return hash; } As with any general hashing function, collisions are possible. Example: "Ea" and "FB" have the same hash value. Early versions of Java examined only the first 16 characters. For some common data this led to poor hash table performance.

9 Collisions collision: When hash function maps 2 values to same index. set.add(11); set.add(49); set.add(24); set.add(7); set.add(54); // collides with 24! collision resolution: An algorithm for fixing collisions. index value

10 Probing probing: Resolving a collision by moving to another index. linear probing: Moves to the next index. set.add(11); set.add(49); set.add(24); set.add(7); set.add(54); // collides with 24; must probe Is this a good approach? variation: quadratic probing moves increasingly far away index value

11 Clustering clustering: Clumps of elements at neighboring indexes. slows down the hash table lookup; you must loop through them. set.add(11); set.add(49); set.add(24); set.add(7); set.add(54); // collides with 24 set.add(14); // collides with 24, then 54 set.add(86); // collides with 14, then 7 How many indexes must a lookup for 94 visit? index value index value

12 Chaining chaining: Resolving collisions by storing a list at each index. add/search/remove must traverse lists, but the lists are short impossible to "run out" of indexes, unlike with probing index value

13 Hash set code import java.util.*; // for List, LinkedList public class HashIntSet { private static final int CAPACITY = 137; private List [] elements; // constructs new empty set public HashSet() { elements = (List []) (new List[CAPACITY]); } // adds the given value to this hash set public void add(int value) { int index = hashFunction(value); if (elements[index] == null) { elements[index] = new LinkedList (); } elements[index].add(value); } // hashing function to convert objects to indexes private int hashFunction(int value) { return Math.abs(value) % elements.length; }...

14 Hash set code 2... // Returns true if this set contains the given value. public boolean contains(int value) { int index = hashFunction(value); return elements[index] != null && elements[index].contains(value); } // Removes the given value from the set, if it exists. public void remove(int value) { int index = hashFunction(value); if (elements[index] != null) { elements[index].remove(value); }

15 Rehashing rehash: Growing to a larger array when the table is too full. Cannot simply copy the old array to a new one. (Why not?) load factor: ratio of (# of elements ) / (hash table length ) many collections rehash when load factor ≅.75 can use big prime numbers as hash table sizes to reduce collisions

16 Rehashing code... // Grows hash array to twice its original size. private void rehash() { List [] oldElements = elements; elements = (List []) new List[2 * elements.length]; for (List list : oldElements) { if (list != null) { for (int element : list) { add(element); }

17 Other questions How would we implement toString on a HashSet ? index value current element:24 current index: 4 sub-index: 0 iterator

18 Implementing a hash map A hash map is just a set where the lists store key/value pairs: // key value map.put("Marty", 14); map.put("Jeff", 21); map.put("Kasey", 20); map.put("Stef", 35); Instead of a List, write an inner Entry node class with key and value fields; the map stores a List index value "Jeff"21 "Marty"14 "Kasey"20 "Stef"35

19 Implementing generics // a parameterized (generic) class public class name {... } Forces any client that constructs your object to supply a type. Don't write an actual type such as String; the client does that. Instead, write a type variable name such as E (for "element") or T (for "type"). You can require multiple type parameters separated by commas. The rest of your class's code can refer to that type by name.