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

Similar documents
CSE 331 Lecture 4. Comparing objects; cloning

CSE 331. Mutation and immutability

Building Java Programs. Inheritance and Polymorphism

CSE 143 Lecture 22. The Object class; Polymorphism. read slides created by Marty Stepp and Ethan Apter

Building Java Programs

The Comparable Interface. reading: 10.2

Super-Classes and sub-classes

Building Java Programs. Interfaces and Comparable reading: , 10.2, 16.4

CSE 143. Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

INHERITANCE. Spring 2019

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Domain-Driven Design Activity

BBM 102 Introduction to Programming II

Programming Languages and Techniques (CIS120)

CIT 590 Homework 6 Fractions

Abstract Classes and Interfaces

The class Object. Lecture CS1122 Summer 2008

Fundamental Java Methods

Building Java Programs Chapter 10

Exercise. Building Java Programs Chapter 10. Naive solution. Collections

Methods Common to all Classes

Objects and Iterators

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

Building Java Programs

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

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

C12a: The Object Superclass and Selected Methods

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

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Introduction to Inheritance

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

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

CMSC 341. Nilanjan Banerjee

BBM 102 Introduction to Programming II Spring 2017

CLASS DESIGN. Objectives MODULE 4

Programming Languages and Techniques (CIS120)

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

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

Exercise. Write a program that reads a file and displays the words of that file as a list.

CS 112 Introduction to Programming

Course Supervisor: Dr. Humera Tariq Hands on Lab Sessions: Ms. Sanya Yousuf

Advanced Topics on Classes and Objects

1 Shyam sir JAVA Notes

USAL1J: Java Collections. S. Rosmorduc

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

CMSC 132: Object-Oriented Programming II

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Programming Languages and Techniques (CIS120)

Programming II (CS300)

Programming Languages and Techniques (CIS120)

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

java.lang.object: Equality

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

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

Error Handling. public int divide(double a, double b) { if (b==0) return -1; // error double result = a/b; return 0; // success }

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Programming Languages and Techniques (CIS120)

ITI Introduction to Computing II

Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

Introduction to Programming Using Java (98-388)

Building Java Programs

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

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

Polymorphism. return a.doublevalue() + b.doublevalue();

Object Oriented Design: Building a Fraction Class

ITI Introduction to Computing II

Garbage collec,on Parameter passing in Java. Sept 21, 2016 Sprenkle - CSCI Assignment 2 Review. public Assign2(int par) { onevar = par; }

Java Classes, Inheritance, and Interfaces

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

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Programming Languages and Techniques (CIS120e)

Programming via Java Defining classes

Java Magistère BFA

Object Oriented Modeling

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

Lecture 11: Intro to Classes

Introduction to Visual Basic and Visual C++ Introduction to Java. JDK Editions. Overview. Lesson 13. Overview

Inheritance. The Java Platform Class Hierarchy

Operations. I Forgot 9/4/2016 COMPUTER SCIENCE DEPARTMENT PICNIC. If you forgot your IClicker, or your batteries fail during the exam

Advanced Placement Computer Science. Inheritance and Polymorphism

Rules and syntax for inheritance. The boring stuff

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

JAVA MOCK TEST JAVA MOCK TEST II

Programming Languages and Techniques (CIS120)

Inheritance (Part 5) Odds and ends

Lecture 12: Classes II

Building Java Programs

CS260 Intro to Java & Android 03.Java Language Basics

The Liskov Substitution Principle

CSE 331 Software Design & Implementation

Core Java - SCJP. Q2Technologies, Rajajinagar. Course content

Java Fundamentals (II)

ITI Introduction to Computing II

ITI Introduction to Computing II

CSE 331 Software Design & Implementation

Test Class A. public class A { private int x, y; public int getx() { return x; } public int gety() { return y; }

Transcription:

CSE 373 Objects in Collections: Object; equals; compareto; mutability slides created by Marty Stepp http://www.cs.washington.edu/373/ University of Washington, all rights reserved. 1

Recall: A typical Java class public class Point { private int x; // fields private int y; public Point(int x, int y) { // constructor this.x = x; this.y = y; public int getx() { return x; // accessor public int gety() { return y; public void translate(int dx, int dy) { x += dx; y += dy; // mutator public String tostring() { // for printing return "(" + x + ", " + y + ")"; 2

The class Object The class Objectforms the root of the overall inheritance tree of all Java classes. Every class is implicitly a subclass of Object The Object class defines several methods that become part of every class you write. For example: public String tostring() Returns a text representation of the object, usually so that it can be printed. 3

Object methods method protected Object clone() public boolean equals(object o) protected void finalize() public Class<?> getclass() public int hashcode() public String tostring() public void notify() public void notifyall() public void wait() public void wait(...) description creates a copy of the object returns whether two objects have the same state called during garbage collection info about the object's type a code suitable for putting this object into a hash collection text representation of the object methods related to concurrency and locking (seen later) What does this list of methods tell you about Java's design? 4

Recall: comparing objects The ==operator does not work well with objects. == tests for referential equality, not state-based equality. It produces trueonly when you compare an object to itself. Point p1 = new Point(5, 3); Point p2 = new Point(5, 3); Point p3 = p2; // p1 == p2 is false; // p1 == p3 is false; // p2 == p3 is true p1 p2 x 5 y 3... x 5 y 3 // p1.equals(p2)? // p2.equals(p3)? p3... 5

Default equals method The Object class's equals implementation is very simple: public class Object {... public boolean equals(object o) { return this == o; However: When we have used equals with various kinds of objects, it didn't behave like ==. Why not? Classes can override equals to provide their own equality test. The Java API documentation for equals is elaborate. Why? The equality test must meet various guidelines to be a proper test. 6

Flawed equals method 1 public boolean equals(point other) { // bad if (x == other.x && y == other.y) { return true; else { return false; Let's write an equalsmethod for a Pointclass. The method should compare the state of the two objects and return trueif they have the same x/yposition. What's wrong with the above implementation? 7

Flaws in the method The body can be shortened to the following (boolean zen): return x == other.x && y == other.y; The parameter to equals must be of type Object, not Point. It should be legal to compare a Pointto any other object: // this should be allowed Point p = new Point(7, 2); if (p.equals("hello")) { // false... equals should always return false if a non-point is passed. By writing ours to accept a Point, we have overloadedequals. Point has two equals methods: One takes an Object, one takes a Point. 8

Flawed equals method 2 public boolean equals(object o) { // bad return x == o.x && y == o.y; What's wrong with the above implementation? It does not compile: Point.java:36: cannot find symbol symbol : variable x location: class java.lang.object return x == o.x && y == o.y; ^ The compiler is saying, "ocould be any object. Not every object has an xfield." 9

The instanceof keyword reference instanceof type if (variable instanceof type) { statement(s); A binary, infix, boolean operator. Tests whether variable refers to an object of class type (or any subclass of type). String s = "hello"; Point p = new Point(); expression s instanceof Point s instanceof String p instanceof Point p instanceof String p instanceof Object s instanceof Object null instanceof String null instanceof Object result false true true false true true false false 10

Correct equals method // Returns true if o refers to a Point object // with the same (x, y) coordinates as // this Point; otherwise returns false. public boolean equals(object o) { if (o instanceof Point) { Point other = (Point) o; return x == other.x && y == other.y; else { return false; Casting references is different than casting primitives. Doesn't actually change the object that is referred to. Tells the compiler to assume that orefers to a Pointobject. 11

Comparing objects Operators like <and >do not work with objects in Java. But we do think of some types as having an ordering (e.g. Dates). (In other languages, we can enable <, > with operator overloading.) natural ordering: Rules governing the relative placement of all values of a given type. Implies a notion of equality (like equals) but also < and >. total ordering: All elements can be arranged in A B C... order. comparison function: Code that, when given two values Aand Bof a given type, decides their relative ordering: A < B, A == B, A > B 12

The Comparable interface The standard way for a Java class to define a comparison function for its objects is to implement the Comparable interface. public interface Comparable<T> { public int compareto(t other); A call of A.compareTo(B) should return: a value < 0 if Acomes "before" Bin the ordering, a value > 0 if Acomes "after" Bin the ordering, orexactly 0 if Aand Bare considered "equal" in the ordering. 13

compareto example public class Point implements Comparable<Point> { // sort by x and break ties by y public int compareto(point other) { if (x < other.x) { return -1; else if (x > other.x) { return 1; else if (y < other.y) { return -1; // same x, smaller y else if (y > other.y) { return 1; // same x, larger y else { return 0; // same x and same y 14

compareto tricks subtraction trick - Subtracting ints works well for compareto: public int compareto(point other) { if (x!= other.x) { return x - other.x; // sort by x first else { return y - other.y; // if same x, break tie by y The idea: if x > other.x, then x - other.x > 0 if x < other.x, then x - other.x < 0 if x == other.x, then x - other.x == 0 To easily compare two doubles, try Double.compare: public int compareto(employee other) { return Double.compare(salary, other.salary); 15

compareto tricks 2 delegation trick-if your object's fields are comparable (such as strings), use their compareto results to help you: // compare by name, e.g. "Joe" < "Suzy" public int compareto(employee other) { return name.compareto(other.getname()); Guava has a nice ComparisonChain class for comparisons: // compare by name, break tie by salary, then id public int compareto(employee other) { return ComparisonChain.start().compare(name, other.name).compare(salary, other.salary).compare(id, other.id).result(); 16

compareto and equals compareto should generally be consistent with equals. a.compareto(b) == 0 should imply that a.equals(b). equals-comparetotrick-if your class needs to implement both equals and compareto, you can take advantage: public boolean equals(object o) { if (o instanceof Employee) { Employee other = (Employee) o; return this.compareto(other) == 0; else { return false; 17

compareto and collections Java's binary search methods call compareto internally. String[] a = {"al", "bob", "cari", "dan", "mike"; int index = Arrays.binarySearch(a, "dan"); // 3 Java's TreeSet/Map use compareto internally for ordering. Only classes that implement Comparable can be used as elements. Set<String> set = new TreeSet<String>(); for (int i = a.length - 1; i >= 0; i--) { set.add(a[i]); System.out.println(s); // [al, bob, cari, dan, mike] 18

Mutation mutation: A modification to the state of an object. Point p = new Point(3, 5); p.translate(1, 3); // mutator; (4, 8) immutable: Unable to be changed (mutated). Java example: Strings (can't change one, only produce a new one) Why? What is good about immutability? easier to design, implement, and use immutable objects less prone to developer error, misuse by clients more secure (sometimes) can be optimized for better performance / memory use (sometimes) 19

Making a class immutable 1. Don't provide any methods that modify the object's state. 2. Ensure that the class cannot be extended. 3. Declare all fields final (unable to be modified once set). local variables (value can be set once, and can never be changed) fields (they can be set only once, in the constructor) static fields (they become "class constants") classes (the class becomes unable to be subclassed) methods (the method becomes unable to be overridden) 4. Declare all fields private. (ensure encapsulation) 5. Ensure exclusive access to any mutable object fields. Don't let a client get a reference to a field that is a mutable object. 20

Mutable Fraction class public class Fraction implements Cloneable, Comparable<Fraction> { private int numerator, denominator; public Fraction(int n) public Fraction(int n, int d) public int getnumerator(), getdenominator() public void setnumerator(int n), setdenominator(int d) public Fraction clone() public int compareto(fraction other) public boolean equals(object o) public String tostring() public void add(fraction other) public void subtract(fraction other) public void multiply(fraction other) public void divide(fraction other) How would we make this class immutable? 21

Immutable Fraction class public final class Fraction implements Comparable<Fraction> { private final int numerator, denominator; public Fraction(int n) public Fraction(int n, int d) public int getnumerator(), getdenominator() // no more setn/d methods // no clone method needed public int compareto(fraction other) public boolean equals(object o) public String tostring() public Fraction add(fraction other) // past mutators public Fraction subtract(fraction other) // are producers public Fraction multiply(fraction other) // (return a new public Fraction divide(fraction other) // object) 22

Immutable methods // mutable version public void add(fraction other) { numerator = numerator * other.denominator + other.numerator * denominator; denominator = denominator * other.denominator; reduce(); // private helper to reduce fraction // immutable version public Fraction add(fraction other) { int n = numerator * other.denominator + other.numerator * denominator; int d = denominator * other.denominator; return new Fraction(n, d); former mutators become producers create/return a new immutable object rather than modifying this one 23

Mutability and collections Set<Time> times = new HashSet<Time>(); times.add(new Time(11, 30, "AM")); times.add(new Time(12, 45, "PM")); Course c = new Course("CSE 373", 3, times,...);... // c will be modified! times.add(new Time(3, 30, "PM")); Since the course stores the set of times passed in, the object is in fact mutable. (called "representation exposure") What could the Courseauthor do to provide an immutable class? copy the set of times in constructor; don't return a direct reference to it in gettimes() 24