HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.

Slides:



Advertisements
Similar presentations
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Advertisements

SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
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.
Hashing as a Dictionary Implementation
1 Class Design CS 3331 Fall Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode method.
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.
Searching and Sorting I 1 Searching and Sorting 1.
1 CSE 326: Data Structures Hash Tables Autumn 2007 Lecture 14.
ICS201 Lecture 20 : Searching King Fahd University of Petroleum & Minerals College of Computer Science & Engineering Information & Computer Science Department.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
1 Exercises: Special Case Search Structures Design super-fast search structures for the following special cases: a)Data consists of ints in the range 0.
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.
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.
Searching. 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.
CSE 373 Data Structures and Algorithms Lecture 18: Hashing III.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
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.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 22 Java Collections.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
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.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
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[]
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.
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.
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.
Utilities (Part 2) Implementing static features 1.
Inheritance (Part 4) Abstract Classes 1.  sometimes you will find that you want the API for a base class to have a method that the base class cannot.
Chapter 18 Java Collections Framework
CS 61B Data Structures and Programming Methodology July 17, 2008 David Sun.
Introduction to Java Java Translation Program Structure
Some Standard Classes Goals The Object class The String class Wrapper classes The Math class Random Numbers.
Goals for Today 1  Multiton  maps  static factory methods.
Mixing Static and Non-static
Hashing as a Dictionary Implementation Chapter 19.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Chapter 11 Hash Anshuman Razdan Div of Computing Studies
Static Attributes and Inheritance  static attributes behave the same as non-static attributes in inheritance  public and protected static attributes.
“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.
Inheritance (Part 5) Odds and ends 1. Static Methods and Inheritance  there is a significant difference between calling a static method and calling a.
Inheritance (Part 2) KomondorBloodHound PureBreedMix Dog Object.
CS 61B Data Structures and Programming Methodology July 2, 2008 David Sun.
Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.
Hash Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
1 Class Design CS 3331 Sec 6.1 & 6.3 of [Jia03]. 2 Outline  Organizing classes  Design guidelines  Canonical forms of classes equals method hashCode.
Mixing Static and Non-static Singleton 1. Singleton Pattern 2  “There can be only one.”  Connor MacLeod, Highlander.
Polymorphism SWE 619. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element.
Week 9 - Friday.  What did we talk about last time?  Collisions  Open addressing ▪ Linear probing ▪ Quadratic probing ▪ Double hashing  Chaining.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
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.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
Sections 10.5 – 10.6 Hashing.
Searching.
CompareTo.
Information hiding.
The hashCode method.
Searching.
Non-static classes.
CSE 1030: Implementing Non-Static Features
Searching.
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

hashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override hashCode() for PhoneNumber // client code somewhere PhoneNumber pizza = new PhoneNumber(416, 967, 1111); HashSet h = new HashSet (); h.add(pizza); System.out.println( h.contains(pizza) ); // true PhoneNumber pizzapizza = new PhoneNumber(416, 967, 1111); System.out.println( h.contains(pizzapizza) ); // false [notes 2.3.5]

Arrays as Containers 2  suppose you have an array of unique PhoneNumber s  how do you compute whether or not the array contains a particular PhoneNumber ? public static boolean hasPhoneNumber(PhoneNumber p, PhoneNumber[] numbers) { if (numbers != null) { for( PhoneNumber num : numbers ) { if (num.equals(p)) { return true; } } } return false; }

3  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 PhoneNumber s in the array:  best case  the first PhoneNumber is the one we are searching for  1 call to equals()  worst case  the PhoneNumber is not in the array  n calls to equals()  average case  the PhoneNumber is somewhere in the middle of the array  approximately (n/2) calls to equals()

Hash Tables 4  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 5  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

Search on a Hash Table 6  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

7  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 PhoneNumber s in the hash table:  best case  the bucket is empty, or the first PhoneNumber in the bucket is the one we are searching for  0 or 1 call to equals()  worst case  all n of the PhoneNumber s are in the same bucket  n calls to equals()  average case  the PhoneNumber is in a bucket with a small number of other PhoneNumbers  a small number of calls to equals()

Object hashCode() 8  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

9  note that pizza and pizzapizza are 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 pizzapizza.equals(pizza) * // client code somewhere PhoneNumber pizza = new PhoneNumber(416, 967, 1111); HashSet h = new HashSet (); h.add(pizza); PhoneNumber pizzapizza = new PhoneNumber(416, 967, 1111); System.out.println( h.contains(pizzapizza) ); // false * unless you're from Naples

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

A Slightly Better hashCode() 11 public final class PhoneNumber { // attributes, constructors, public int hashCode() { return (int)(this.getAreaCode() + this.getExchangeCode() + this.getStationCode()); } }

12  the basic idea is generate a hash code using the attributes 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 13  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?

Comparable Objects 14  many value types have a natural ordering  that is, for two objects x and y, x is less than y is meaningful  Short, Integer, Float, Double, etc  String s can be compared in dictionary order  Date s can be compared in chronological order  you might compare Vector2d s by their length  a PhoneNumber value can be interpreted as a long value  if your class has a natural ordering, consider implementing the Comparable interface  doing so allows clients to sort arrays or Collection s of your object [AJ p ], [notes 2.2.4]

Interfaces 15  an interface is (usually) a group of related methods with empty bodies  the Comparable interface has just one method public interface Comparable { int compareTo(T t); }  a class that implements an interfaces promises to provide an implementation for every method in the interface

compareTo() 16  Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.  Throws a ClassCastException if the specified object type cannot be compared to this object.

PhoneNumber compareTo() 17 public final class PhoneNumber implements Comparable { // attributes, constructors, methods... public int compareTo(PhoneNumber n){ // version 1 Long me = (long)this.getStationCode() + // L * this.getExchangeCode() + // L * this.getAreaCode(); // // Long other = (long)n.getStationCode() + // L * n.getExchangeCode() + // L * n.getAreaCode(); // return me.compareTo(other); // } }

Alternative Implementation 18 public int compareTo(PhoneNumber n) // version 2 { int result = this.compare(this.getAreaCode(), n.getAreaCode()); if (result == 0) { result = this.compare(this.getExchangeCode(), n.getExchangeCode()); if (result == 0) { result = this.compare(this.getStationCode(), n.getStationCode()); } } return result; } private helper method

Alternative Implementation (cont.) 19 private int compare(short a, short b) { Short x = a; Short y = b; return x.compareTo(y); }

> >> == Comparable Contract the sign of the returned int must flip if the order of the two compared objects flip  if x.compareTo(y) 0 then y.compareTo(x) 0 2. compareTo() must be transitive  if x.compareTo(y) 0 && y.compareTo(z) 0 then x.compareTo(z) 0 3. if x.compareTo(y) == 0 then the signs of x.compareTo(z) and y.compareTo(z) must be the same <>><== < <<

Not in the Comparable Contract 21  it is not required that compareTo() be consistent with equals()  that is if x.compareTo(y) == 0 then x.equals(y) == false is acceptable  similarly if x.equals(y) == true then x.compareTo(y) != 0 is acceptable  try to come up with examples for both cases above

Mixing Static and Non-Static 22

static Attributes 23  recall (March 06, slide 16)  an attribute that is static is a per-class member  only one copy of the attribute, and the attribute is associated with the class  every object created from a class declaring a static attribute shares the same copy of the attribute  static attributes are used when you really want only one common instance of the attribute for the class

Example 24  the most common textbook example of a static attribute is a counter that counts the number of created instances of your class // adapted from Sun's Java Tutorial public class Bicycle { // some attributes here... private static int numberOfBicycles = 0; public Bicycle() { // set some attributes here... Bicycle.numberOfBicycles++; } public static int getNumberOfBicyclesCreated() { return Bicycle.numberOfBicycles; } } note: not this.numberOfBicycles++ [notes 3.2]

25  another common example is to count the number of times a method has been called public class X { private static int numTimesXCalled = 0; private static int numTimesYCalled = 0; public void xMethod() { // do something... and then update counter ++X.numTimesXCalled; } public void yMethod() { // do something... and then update counter ++X.numTimesYCalled; } }

26  constants are often static attributes public class SolarSystemSimulator { private static final double G = e-11; private static final double EARTH_MASS = e24; public double gravitationalForceEarth(double mass, double dist) { return SolarSystemSimulator.G * EARTH_MASS * mass / (dist * dist); } }

27  draw the memory diagram for the following fragment of code SolarSystemSimulator s = new SolarSystemSimulator(); double satMass = ; double satOrbitalRadius = e7; double force; force = s. gravitationalForceEarth(satMass, satOrbitalRadius);