== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011.

Slides:



Advertisements
Similar presentations
More on Classes Inheritance and Polymorphism
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
Composition CMSC 202. Code Reuse Effective software development relies on reusing existing code. Code reuse must be more than just copying code and changing.
Programo Issues Cora Pérez Ariza ~ DECSAI ~ UGR Granada, January 28 th & 29 th, 2009.
Effective Java, Chapter 3: Methods Common to All Objects.
Effective Java, Chapter 3: Methods Common to All Objects Paul Ammann.
Equality Programming in C# Equality CSE 494R (proposed course for 459 Programming in C#) Prof. Roger Crawfis.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
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.
CS2200 Software Development Lecture: Object class A. O’Riordan, 2008.
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.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Inheritance Part II. Lecture Objectives To learn about inheritance To understand how to inherit and override superclass methods To be able to invoke superclass.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
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.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Equality CSE 331 University of Washington. Object equality A simple idea - we have intuitions about equality: - Two objects are equal if they have the.
CSC 142 O 1 CSC 142 Java More About Inheritance & Interfaces [Reading: chapter 13]
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.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
CSE 331 SOFTWARE DESIGN & IMPLEMENTATION MIDTERM REVIEW Autumn 2011.
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.
CS 61B Data Structures and Programming Methodology July 3, 2008 David Sun.
CSE 331 Software Design & Implementation Hal Perkins Winter 2013 ==, equals(), and all that (Slides by David Notkin and Mike Ernst) 1.
Fall 2010 UVa David Evans cs2220: Engineering Software Class 27: Exam 2.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
Symbol Tables From “Algorithms” (4 th Ed.) by R. Sedgewick and K. Wayne.
Object Oriented Programming
Operator Overloading Week 5.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
CMSC 202 Inheritance II. Version 10/092 Inherited Constructors? An Employee constructor cannot be used to create HourlyEmployee objects. Why not? We must.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
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.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Relations.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
COMP 110 Some notes on inheritance, review Luv Kohli December 1, 2008 MWF 2-2:50 pm Sitterson 014.
1 CSE 331 The Object class; Object equality and the equals method slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Testing (final thoughts). equals() and hashCode() Important when using Hash-based containers class Duration { public final int min; public final int sec;
1 clone() Defined in Object Creates an identical copy –Copies pointers to fields (does not copy fields of fields) –Makes a shallow copy if the object’s.
Searching.
CSC 205 Java Programming II
CSE 331 Software Design and Implementation
Testing, cont., Equality and Identity
CSE 331 Software Design and Implementation
Extending Classes.
Java Programming Language
Equality, conclusion Based on material by Michael Ernst, University of Washington.
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Searching.
Lecture 25: Inheritance and Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
CIS 110: Introduction to computer programming
CS 240 – Advanced Programming Concepts
Presentation transcript:

== equals ? CSE 331 SOFTWARE DESIGN & IMPLEMENTATION EQUALITY Autumn 2011

Programming: object equality  The basic intuition is simple: two objects are equal if they are indistinguishable (have the same value)  But our intuitions are incomplete in subtle ways  Must the objects be the same object or “just” indistinguishable?  What is an object’s value? How do we interpret “the bits”?  What does it mean for two collections of objects to be equal? Does each need to hold the same objects? In the same order? What if a collection contains itself? Who decides? The programming language designer? You?  If a program uses inheritance, does equality change?  Is equality always an efficient operation? Is equality temporary or forever? CSE 331 Autumn

Equality: hard in reality as well  Using DNA, which of two identical twins committed a crime?  “My grandfather’s axe”: after repeatedly replacing an axe’s head and handle, is it still the same axe?  If you are flying next to someone on an airplane, are you on the same flight? The same airline?  And then there are really hard questions like social equality, gender equality, race equality, equal opportunity, etc.! CSE 331 Autumn

Properties of equality: for any useful notion of equality  Reflexive a.equals(a)  3  3 would be confusing  Symmetric a.equals(b)  b.equals(a)  3 = 4  4  3 would be confusing  Transitive a.equals(b)  b.equals(c)  a.equals(c)  ((1+2) = 3  3 = (5-2))  ((1+2)  (5-2)) would be confusing A relation that is reflexive, transitive, and symmetric is an equivalence relation 4

Reference equality  The simplest and strongest (most restrictive) definition is reference equality  a == b if and only if a and b refer (point) to the same object  Easy to show that this definition ensures == is an equivalence relation Duration d1 = new Duration(5,3); Duration d2 = new Duration(5,3); Duration d3 = p2; // T/F: d1 == d2 ? // T/F: d1 == d3 ? // T/F: d2 == d3 ? // T/F: d1.equals(d2) ? // T/F: d2.equals(d3) ? min5sec3 min5sec3 d1 d2 d3 CSE 331 Autumn

Object.equals method public class Object { public boolean equals(Object o) { return this == o; } }  This implements reference equality  What about the specification of Object.equals ?  It’s a bit more complicated… CSE 331 Autumn

public boolean equals(Object obj)Object Indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation: [munch – definition of equivalence relation] It is consistent: for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the object is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object ( x==y has the value true ). … [munch] Parameters & Returns & See Also CSE 331 Autumn 2011

The Object contract  Why complicated? Because the Object class is designed for inheritance  Its specification will apply to all subtypes – that is, all Java subclasses – so its specification must be flexible  If a.equals(b) were specified to test a == b, then no class could change this and still be a subtype of Object  Instead the specification gives the basic properties that clients can rely on it to have in all subtypes of Object  Object ’s implementation of equals as a == b satisfies these properties but the specification is more flexible CSE 331 Autumn

Comparing objects less strictly public class Duration { private final int min; private final int sec; public Duration(int min, int sec) { this.min = min; this.sec = sec; } } … Duration d1 = new Duration(10,5); Duration d2 = new Duration(10,5); System.out.println(d1.equals(d2)); false – but we likely prefer it to be true CSE 331 Autumn

An obvious improvement public boolean equals(Duration d) { return d.min == min && d.sec == sec; }  This defines an equivalence relation for Duration objects (proof by partial example and handwaving) Duration d1 = new Duration(10,5); Duration d2 = new Duration(10,5); System.out.println(d1.equals(d2)); Object o1 = new Duration(10,5); Object o2 = new Duration(10,5); System.out.println(o1.equals(o2)); // False! But oops CSE 331 Autumn

overloading  Defining equals in the Duration class creates a method that is invoked upon executing d.equals(…) where d is a declared instance of Duration  This co-exists with equals in the Object class that is invoked upon executing o.equals(…) where o is a declared instance of Object – even if it refers to an instance of Duration  This gives two equals methods that can be invoked on instances of Duration with different results CSE 331 Autumn

@Override equals in // compiler warning if type mismatch public boolean equals(Object o) { if (! (o instanceof Duration)) // Parameter must also be return false; // a Duration instance Duration d = (Duration) o; // cast to treat o as // a Duration return d.min == min && d.sec == sec; } Object d1 = new Duration(10,5); Object d2 = new Duration(10,5); System.out.println(d1.equals(d2)); // True  overriding re-defines an inherited method from a superclass – same name & parameter list & return type  Duration s now have to be compared as Duration s (or as Object s, but not as a mixture) CSE 331 Autumn

Equality and inheritance  Add a nanosecond field for fractional seconds public class NanoDuration extends Duration { private final int nano; public NanoDuration(int min, int sec, int nano) { super(min, sec); this.nano = nano; }  Inheriting equals() from Duration ignores nano so Duration instances with different nano s will be equal CSE 331 Autumn

equals : account for nano public boolean equals(Object o) { if (! (o instanceof NanoDuration)) return false; NanoDuration nd = (NanoDuration) o; return super.equals(nd) && nano == nd.nano; } But this is not symmetric! Duration d1 = new NanoDuration(5,10,15); Duration d2 = new Duration(5,10); System.out.println(d1.equals(d2)); // false System.out.println(d2.equals(d1)); // true Oops! CSE 331 Autumn

Let’s get symmetry public boolean equals(Object o) { if (! (o instanceof Duration)) return false; // if o is a normal Duration, compare without nano if (! (o instanceof NanoDuration)) return super.equals(o); NanoDuration nd = (NanoDuration) o; return super.equals(nd) && nano == nd.nano; } But this is not transitive! Duration d1 = new NanoDuration(5,10,15); Duration d2 = new Duration(5,10); Duration d3 = new NanoDuration(5,10,30); System.out.println(d1.equals(d2)); // true System.out.println(d2.equals(d3)); // true System.out.println(d1.equals(d3)); // false! Oops! CSE 331 Autumn

Replaces earlier version if (! (o instanceof Duration)) return false; Fix in public boolean equals(Object o) { if (o == null) return false; if (! o.getClass().equals(getClass())) return false; Duration d = (Duration) o; return d.min == min && d.sec == sec; }  Check exact class instead of instanceOf  Equivalent change in NanoDuration CSE 331 Autumn

General issues  Every subtype must override equals – even if it wants the identical definition  Take care when comparing subtypes to one another  On your own: Consider an ArithmeticDuration class that adds operators but no new fields CSE 331 Autumn

Another solution: avoid inheritance  Use composition instead public class NanoDuration { private final Duration duration; private final int nano; //... }  Now instances of NanoDuration and of Duration are unrelated – there is no presumption that they can be equal or unequal or even compared to one another…  Solves some problems, introduces others – for example, can’t use NanoDuration s where Duration s are expected (because one is not a subtype of the other) CSE 331 Autumn

Efficiency of equality  Equality tests can be slow: Are two objects with millions of sub- objects equal? Are two video files equal?  It is often useful to quickly pre-filter – for example if (video1.length() != video2.length()) return false else do full equality check  Java requires each class to define a standard pre-filter – a hashCode() method that produces a single hash value (a 32- bit signed integer) from an instance of the class  If two objects have different hash codes, they are guaranteed to be different  If they have the same hash code, they may be equal objects and should be checked in full Unless you define hashCode() improperly!!! CSE 331 Autumn

specification for Object.hashCode  public int hashCode()  “Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.HashMap.”  The general contract of hashCode is  Deterministic: o.hashCode() == o.hashCode()...so long as o doesn’t change between the calls  Consistent with equality a.equals(b)  a.hashCode()==b.hashCode() Change equals() ? Must you update hashCode ()? ALMOST ALWAYS! I MEAN ALWAYS! This is a sadly common example of the epic fail CSE 331 Autumn

Duration hashCode implementations public int hashCode() { return 1; // always safe, no pre-filtering } public int hashCode() { return min; // safe, inefficient for Durations // differing only in sec field } public int hashCode() { return min+sec; // safe and efficient } public int hashCode() { return new Random().newInt(50000); // danger! danger! } CSE 331 Autumn

Equality, mutation, and time  If two objects are equal now, will they always be equal ?  In mathematics, “yes”  In Java, “you choose” – the Object contract doesn't specify this (but why not?)  For immutable objects, equality is inherently forever  The object’s abstract value never changes (much more on “abstract value” in the ADT lectures) – very roughly, these are the values the client of a class uses (not the representation used internally)  For mutable objects, equality can either  Compare abstract values field-by-field or  Be eternal (how can a class with mutable instances have eternal equality?)  But not both CSE 331 Autumn

Next steps CSE 331 Autumn  Assignment 1  Due Friday 11:59PM  Assignment 2  out Friday  due in two parts, see calendar  Lectures  Abstract data types (F, M)

CSE 331 Autumn