Not overriding equals

Similar documents
For this section, we will implement a class with only non-static features, that represents a rectangle

Domain-Driven Design Activity

Review. CSE 143 Java. A Magical Strategy. Hash Function Example. Want to implement Sets of objects Want fast contains( ), add( )

Hash tables. hashing -- idea collision resolution. hash function Java hashcode() for HashMap and HashSet big-o time bounds applications

The class Object. Lecture CS1122 Summer 2008

CMSC 132: Object-Oriented Programming II. Hash Tables

The Object Class. java.lang.object. Important Methods In Object. Mark Allen Weiss Copyright 2000

Fundamental Java Methods

Linked lists (6.5, 16)

Compsci 201 Hashing. Jeff Forbes February 7, /7/18 CompSci 201, Spring 2018, Hashiing

java.lang.object: Equality

Midterm Exam 2 CS 455, Spring 2015

Outline. 1 Hashing. 2 Separate-Chaining Symbol Table 2 / 13

Creating an Immutable Class. Based on slides by Prof. Burton Ma

Inheritance (Part 5) Odds and ends

Prelim 2. CS 2110, 16 November 2017, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

USAL1J: Java Collections. S. Rosmorduc

Section 05: Midterm Review

COM1020/COM6101: Further Java Programming

CS 310: Hashing Basics and Hash Functions

Homework 4: Hash Tables Due: 5:00 PM, Mar 9, 2018

Prelim 2 SOLUTION. CS 2110, 16 November 2017, 7:30 PM Total Question Name Short Heaps Tree Collections Sorting Graph

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

Expected properties of equality

Faculty of Science FINAL EXAMINATION

Data Structures and Object-Oriented Design VIII. Spring 2014 Carola Wenk

CMSC 132: Object-Oriented Programming II. Effective Java. Department of Computer Science University of Maryland, College Park

CSE373 Fall 2013, Second Midterm Examination November 15, 2013

CSE 331 Software Design & Implementation

Java Fundamentals (II)

INSTRUCTIONS TO CANDIDATES

CS 3410 Ch 20 Hash Tables

Canonical Form. No argument constructor Object Equality String representation Cloning Serialization Hashing. Software Engineering

COMP 250. Lecture 30. inheritance. overriding vs overloading. Nov. 17, 2017

Topic 22 Hash Tables

equals() in the class Object

CSE 331 Software Design & Implementation

CS 310: Hash Table Collision Resolution

Introducing Hashing. Chapter 21. Copyright 2012 by Pearson Education, Inc. All rights reserved

CS61B Lecture #24: Hashing. Last modified: Wed Oct 19 14:35: CS61B: Lecture #24 1

Abstract Data Types (ADTs) Queues & Priority Queues. Sets. Dictionaries. Stacks 6/15/2011

Section 05: Solutions

Equality in.net. Gregory Adam 07/12/2008. This article describes how equality works in.net

(b) Draw a hash table having 10 buckets. Label the buckets 0 through 9.

STANDARD ADTS Lecture 17 CS2110 Spring 2013

Programming Languages and Techniques (CIS120)

Methods Common to all Classes

Hash table basics mod 83 ate. ate. hashcode()

Exam 2 CSCI 2600 Principles of Software November 3, 2015

Super-Classes and sub-classes

Program development plan

Figure 1: Chaining. The implementation consists of these private members:

6.005 Elements of Software Construction Fall 2008

CS61BL Summer 2013 Midterm 2

Total Score /1 /20 /41 /15 /23 Grader

Chapter 11: Collections and Maps

Collections. Powered by Pentalog. by Vlad Costel Ungureanu for Learn Stuff

COMP 250. Lecture 27. hashing. Nov. 10, 2017

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

COMP 250 Fall inheritance Nov. 17, 2017

Programming Languages and Techniques (CIS120e)

CSE 373. Objects in Collections: Object; equals; compareto; mutability. slides created by Marty Stepp

School of Computer Science CPS109 Course Notes 6 Alexander Ferworn Updated Fall 15. CPS109 Course Notes 6. Alexander Ferworn

CSE 331 Midterm Exam Sample Solution 2/18/15

Announcements. Container structures so far. IntSet ADT interface. Sets. Today s topic: Hashing (Ch. 10) Next topic: Graphs. Break around 11:45am

Equality. Michael Ernst. CSE 331 University of Washington

Recap. List Types. List Functionality. ListIterator. Adapter Design Pattern. Department of Computer Science 1

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

NAME: c. (true or false) The median is always stored at the root of a binary search tree.

Programming Languages and Techniques (CIS120)

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

Introduction hashing: a technique used for storing and retrieving information as quickly as possible.

Hashing. Reading: L&C 17.1, 17.3 Eck Programming Course CL I

Collections, Maps and Generics

Java HashMap Interview Questions

Computer Science 136. Midterm Examination

CSE wi Final Exam 3/12/18. Name UW ID#

CS1007: Object Oriented Design and Programming in Java. Lecture #18 Mar 28 Shlomo Hershkop Announcement

Logistics. Homework 10 due tomorrow Review on Monday. Final on the following Friday at 3pm in CHEM 102. Come with questions

CSCI 200 Lab 3 Using and implementing sets

Computer Science 136. Midterm Examination

Data Structures Brett Bernstein

COE318 Lecture Notes Week 6 (Oct 10, 2011)

Class design guidelines. Most of this material comes from Horstmann, Cay: Object-Oriented Design & Patterns (chapter 3)

Programming Languages and Techniques (CIS120)

JAVA MOCK TEST JAVA MOCK TEST II

Primitive vs Reference

Formal Methods of Software Design, Eric Hehner, segment 24 page 1 out of 5

Dynamic Dictionaries. Operations: create insert find remove max/ min write out in sorted order. Only defined for object classes that are Comparable

COE318 Lecture Notes Week 8 (Oct 24, 2011)

CS2110: Software Development Methods. Maps and Sets in Java

Programming Languages and Techniques (CIS120)

1.00/1.001 Introduction to Computers and Engineering Problem Solving. Final Exam

Java Persistence API (JPA) Entities

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

(b) Draw a hash table having 10 buckets. Label the buckets 0 through 9.

CS11 Java. Winter Lecture 8

Hashing. It s not just for breakfast anymore! hashing 1

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

CSE wi Final Exam 3/12/18 Sample Solution

Transcription:

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<Complex> list = new ArrayList<Complex>(); 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<Complex> set = new HashSet<Complex>(); 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<Complex, String> map = new TreeMap<Complex, String>(); 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

5 hashcode

hashcode 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<Complex> h = new HashSet<Complex>(); h.add(y); System.out.println( h.contains(y) ); // true Complex z = new Complex(1, -2); System.out.println( h.contains(z) ); // false 6 [notes 3.3.5]

Arrays as Containers 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; 7

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() 8

Hash Tables you can think of a hash table as being an array of buckets where each bucket holds the stored objects 0 1 2 3... N 9

Insertion into a Hash Table to insert an object a, the hash table calls a.hashcode() method to compute which bucket to put the object into c.hashcode() d.hashcode() N N b.hashcode() 0 a.hashcode() 2 0 1 2 3... N 10 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 to insert an object a, the hash table calls a.hashcode() method to compute which bucket to put the object into b a c d 0 1 2 3... N 11

Search on a Hash Table 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 z.hashcode() N a.hashcode() 2 b a.equals( a ) z.equals( c ) true z.equals( d ) false 0 1 2 3... N 12

Search on a Hash Table 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 z.hashcode() N a.hashcode() 2 b a.equals( a ) z.equals( c ) true z.equals( d ) false 0 1 2 3... N 13

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() 14

Object hashcode() 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 15

// client code somewhere Complex y = new Complex(1, -2); HashSet<Complex> h = new HashSet<Complex>(); h.add(y); Complex z = new Complex(1, -2); System.out.println( h.contains(z) ); // false 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) 16

A Bad (but legal) hashcode public final class Complex { // attributes, constructors, methods... } @Override 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 17

A Slightly Better hashcode public final class Complex { // attributes, constructors, methods... } @Override public int hashcode() { return (int)(this.getreal() + this.getimag()); } 18

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

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 20

Something to Think About 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? 21