Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1.

Slides:



Advertisements
Similar presentations
Garfield AP Computer Science
Advertisements

Singleton vs utility class  at first glance, the singleton pattern does not seem to offer any advantages to using a utility class  i.e., a utility class.
Skip List & Hashing CSE, POSTECH.
Hashing as a Dictionary Implementation
Hashing Chapters What is Hashing? A technique that determines an index or location for storage of an item in a data structure The hash function.
Maps, Dictionaries, Hashtables
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
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.
Maps & Hashing Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
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.
Hashing Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
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.
Sets and Maps (and Hashing)
© The McGraw-Hill Companies, 2006 Chapter 17 The Java Collections Framework.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Sets and Maps Nelson Padua-Perez Bill Pugh Department of Computer Science University of Maryland, College Park.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Hashing Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 206 Introduction to Computer Science II 04 / 06 / 2009 Instructor: Michael Eckmann.
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.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
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.
Data structures and algorithms in the collection framework 1 Part 2.
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.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Non-static classes Part 2 1. Methods  like constructors, all non-static methods have an implicit parameter named this  for methods, this refers to the.
Big Java Chapter 16.
Algorithm Course Dr. Aref Rashad February Algorithms Course..... Dr. Aref Rashad Part: 4 Search Algorithms.
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
Collections. The Plan ● Why use collections? ● What collections are available? ● How are the collections different? ● Examples ● Practice.
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.
Can’t provide fast insertion/removal and fast lookup at the same time Vectors, Linked Lists, Stack, Queues, Deques 4 Data Structures - CSCI 102 Copyright.
Hashing Hashing is another method for sorting and searching data.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
Hashing as a Dictionary Implementation Chapter 19.
LECTURE 35: COLLISIONS CSC 212 – Data Structures.
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Chapter 11 Hash Anshuman Razdan Div of Computing Studies
“Never doubt that a small group of thoughtful, committed people can change the world. Indeed, it is the only thing that ever has.” – Margaret Meade Thought.
CSS446 Spring 2014 Nan Wang.  To understand the implementation of linked lists and array lists  To analyze the efficiency of fundamental operations.
Hash Table March COP 3502, UCF 1. Outline Hash Table: – Motivation – Direct Access Table – Hash Table Solutions for Collision Problem: – Open.
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 From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
1 CSE 331 Hash codes; annotations slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Hash Tables and Hash Maps. DCS – SWC 2 Hash Tables A Set and a Map are both abstract data types – we need a concrete implemen- tation in order to use.
Week 9 - Friday.  What did we talk about last time?  Collisions  Open addressing ▪ Linear probing ▪ Quadratic probing ▪ Double hashing  Chaining.
Hashing. Search Given: Distinct keys k 1, k 2, …, k n and collection T of n records of the form (k 1, I 1 ), (k 2, I 2 ), …, (k n, I n ) where I j is.
Chapter 11 Sets © 2006 Pearson Education Inc., Upper Saddle River, NJ. All rights reserved.
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.
CSE 373: Data Structures and Algorithms Lecture 16: Hashing III 1.
Lecture 9:FXML and Useful Java Collections Michael Hsu CSULA.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Building Java Programs Generics, hashing reading: 18.1.
Sets and Maps Chapter 9.
Sections 10.5 – 10.6 Hashing.
Hashing & HashMaps CS-2851 Dr. Mark L. Hornick.
TCSS 342, Winter 2006 Lecture Notes
The hashCode method.
Searching.
Non-static classes.
CSE 373: Data Structures and Algorithms
Sets, Maps and Hash Tables
Sets and Maps Chapter 9.
Podcast Ch21f Title: HashSet Class
CSE 373 Set implementation; intro to hashing
Presentation transcript:

Not overriding equals  what happens if you do not override equals for a value type class?  all of the Java collections will fail in confusing ways 1

Not overriding equals Complex y = new Complex(1, -2); Complex z = new Complex(1, -2); List list = new ArrayList (); list.add(y); System.out.println("contains (1 - 2i)? " + list.contains(z)); Output: contains (1 - 2i)? false contains uses equals to search the elements of the list 2

Not overriding equals Complex y = new Complex(1, -2); Complex z = new Complex(1, -2); Set set = new HashSet (); set.add(y); System.out.println("add (1 - 2i)? " + set.add(z)); Output: add (1 - 2i)? true add uses equals to search the elements of the set 3

Not overriding equals Complex y = new Complex(1, -2); Complex z = new Complex(1, -2); Map map = new TreeMap (); map.put(y, y.toString()); System.out.println("contains (1 - 2i)? " + map.put(z, z.toString())); Output: contains (1 - 2i)? null put uses equals to search the elements of the map 4

hashCode 5

6  if you override equals you must override hashCode  otherwise, the hashed containers won't work properly  recall that we did not override hashCode for Complex // client code somewhere Complex y = new Complex(1, -2); HashSet h = new HashSet (); h.add(y); System.out.println( h.contains(y) ); // true Complex z = new Complex(1, -2); System.out.println( h.contains(z) ); // false [notes 3.3.5]

Arrays as Containers 7  suppose you have an array of unique Complex numbers  how do you compute whether or not the array contains a particular Complex number?  write a loop to examine every element of the array public static boolean hasNumber(Complex z, Complex[] numbers) { for( Complex num : numbers ) { if (num.equals(z)) { return true; } } return false; }

8  called linear search or sequential search  doubling the length of the array doubles the amount of searching we need to do  if there are n Complex numbers in the array:  best case  the first Complex number is the one we are searching for  1 call to equals()  worst case  the Complex number is not in the array  n calls to equals()  average case  the Complex number is somewhere in the middle of the array  approximately (n/2) calls to equals()

Hash Tables 9  you can think of a hash table as being an array of buckets where each bucket holds the stored objects N

Insertion into a Hash Table 10  to insert an object a, the hash table calls a.hashCode() method to compute which bucket to put the object into N a.hashCode() 2a b.hashCode() 0b c.hashCode() Nc d.hashCode() Nd means the hash table takes the hash code and does something to it to make it fit in the range 0—N

Insertion into a Hash Table 11  to insert an object a, the hash table calls a.hashCode() method to compute which bucket to put the object into bacdcd N

Search on a Hash Table 12  to see if a hash table contains an object a, the hash table calls a.hashCode() method to compute which bucket to look for a in bacdcd N a.hashCode() 2 z.hashCode() N a.equals( ) true z.equals( ) false z.equals( ) false

Search on a Hash Table 13  to see if a hash table contains an object a, the hash table calls a.hashCode() method to compute which bucket to look for a in bacdcd N a.hashCode() 2 z.hashCode() N a.equals( ) true z.equals( ) false z.equals( ) false

14  searching a hash table is usually much faster than linear search  doubling the number of elements in the hash table usually does not noticably increase the amount of search needed  if there are n Complex numbers in the hash table:  best case  the bucket is empty, or the first Complex in the bucket is the one we are searching for  0 or 1 call to equals()  worst case  all n of the Complex numbers are in the same bucket  n calls to equals()  average case  the Complex number is in a bucket with a small number of other Complex numbers  a small number of calls to equals()

Object hashCode() 15  if you don't override hashCode(), you get the implementation from Object.hashCode()  Object.hashCode() uses the memory address of the object to compute the hash code

16  note that y and z refer to distinct objects  therefore, their memory locations must be different  therefore, their hash codes are different (probably)  therefore, the hash table looks in the wrong bucket (probably) and does not find the phone number even though y.equals(z) // client code somewhere Complex y = new Complex(1, -2); HashSet h = new HashSet (); h.add(y); Complex z = new Complex(1, -2); System.out.println( h.contains(z) ); // false

A Bad (but legal) hashCode 17 public final class Complex { // attributes, constructors, public int hashCode() { return 1; // or any other constant int }  this will cause a hashed container to put all Complex numbers into the same bucket

A Slightly Better hashCode 18 public final class Complex { // attributes, constructors, public int hashCode() { return (int)(this.getReal() + this.getImag()); }

eclipse hashCode  eclipse will generate a hashCode method for you  Source  Generate hashCode() and equals()...  it uses an algorithm that  “... yields reasonably good hash functions, [but] does not yield state-of-the-art hash functions, nor do the Java platform libraries provide such hash functions as of release 1.6. Writing such hash functions is a research topic, best left to mathematicians and theoretical computer scientists. ”  Joshua Bloch, Effective Java 2 nd Edition 19

20  the basic idea is generate a hash code using the fields of the object  it would be nice if two distinct objects had two distinct hash codes  but this is not required; two different objects can have the same hash code  it is required that: 1. if x.equals(y) then x.hashCode() == y.hashCode() 2. x.hashCode() always returns the same value if x does not change its state

Something to Think About 21  what do you need to be careful of when putting a mutable object into a HashSet ?  can you avoid the problem by using immutable objects?