1 CSE 331 Comparing objects; Comparable, compareTo, and Comparator slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R.

Slides:



Advertisements
Similar presentations
Building Java Programs Chapter 10
Advertisements

Generics, Lists, Interfaces
1 CSE 331 Enumerated types ( enum ) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Computer Science 209 Software Development Equality and Comparisons.
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.
Using interfaces Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling How would you find the maximum.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
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.
1 Introduction to Searching and Sorting Comparable Interface -Reading p Comparator Interface.
Unit 261 Introduction to Searching and Sorting Comparable Interface Comparator Interface Algorithm Complexity Classes Exercises.
Introduction to Searching and Sorting
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 10: ArrayList.
CS 106 Introduction to Computer Science I 03 / 17 / 2008 Instructor: Michael Eckmann.
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.
CSE 143 Lecture 7 Sets and Maps reading: ; 13.2 slides created by Marty Stepp
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
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.
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
CSS446 Spring 2014 Nan Wang.  Java Collection Framework ◦ Set ◦ Map 2.
CSE 143 Lecture 15 Binary Search; Comparable reading: 13.2; 10.2 slides created by Marty Stepp
ADSA: Generics/ Advanced Data Structures and Algorithms Objective –to describe basic forms of generic classes, interfaces, and methods for searching.
1 TCSS 143, Autumn 2004 Lecture Notes Creating Java Classes.
Lecture 121 CS110 Lecture 12 Tuesday, March 9, 2004 Announcements –hw5 due Thursday –Spring break next week Agenda –questions –ArrayList –TreeMap.
Sets and Maps Sets Maps The Comparator Interface Sets and Maps in Java Collections API – TreeSet – TreeMap Review for Exam Reading:
1 CSE 331 Generics (Parametric Polymorphism) slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
CSE 143 Lecture 2 More ArrayList ; classes and objects reading: 10.1; slides created by Marty Stepp and Hélène Martin
1 CSE 331 Hash codes; annotations slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Binary search and complexity reading:
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.
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.
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.
Building Java Programs Chapter 12: Recursive public/private pairs Chapter 13: Searching reading: 13.3.
Lecture 23:More on Interfaces
Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2
Collections.
Interfaces.
Lecture 17: Polymorphism (Part II)
Data Structures TreeMap HashMap.
TreeSet TreeMap HashMap
CSE 143 Lecture 14 Searching and Comparable reading: ; 10.2
Building Java Programs Chapter 10
Introduction to Searching and Sorting
Lecture 14: binary search and complexity reading:
Interfaces CS163 Fall 2018.
Topic 33 ArrayList.
Lecture 15: binary search reading:
Building Java Programs
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Review: Classes, Inheritance, and Collections
CSE 143 Lecture 16 (A) Searching and Comparable
Shapes Consider the task of writing classes to represent 2D shapes such as Circle, Rectangle, and Triangle. Certain operations are common to all shapes:
Binary Search Trees continued; Tree Sets
Lexical Ordering and Sorting
Lecture 18: Polymorphism (Part II)
Binary search (13.1) binary search: Locates a target value in a sorted array/list by successively eliminating half of the array from consideration. How.
CSE 373 Objects in Collections: Object; equals; compareTo; mutability
CSE 373 Advanced heap implementation; ordering/Comparator
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 8 Iterators; Comparable reading: 11.2; 10.2
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
slides adapted from Marty Stepp and Hélène Martin
CSE 143 Lecture 14 Searching and Comparable reading: ; 10.2
Presentation transcript:

1 CSE 331 Comparing objects; Comparable, compareTo, and Comparator slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia

2 Comparing objects Operators like do not work with objects in Java.  But we do think of some types as having an ordering (e.g. Date s).  (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.  total ordering: All elements can be arranged in A ≤ B ≤ C ≤... order. comparison function: Code that, when given two values A and B of a given type, decides their relative ordering:  A B

3 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 { public int compareTo(T other); } A call of A.compareTo( B ) should return: a value <0if A comes "before" B in the ordering, a value >0if A comes "after" B in the ordering, orexactly0if A and B are considered "equal" in the ordering. Effective Java Tip #12: Consider implementing Comparable.

4 compareTo example public class Point implements Comparable { // 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 } // subtraction trick: // return (x != other.x) ? (x - other.x) : (y - other.y); }

5 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 set = new TreeSet (); for (int i = a.length - 1; i >= 0; i--) { set.add(a[i]); } System.out.println(s); // [al, bob, cari, dan, mike]

6 Flawed compareTo method public class BankAccount implements Comparable { private String name; private double balance; private int id;... public int compareTo(BankAccount other) { return name.compareTo(other.name); // order by name } public boolean equals(Object o) { if (o != null && getClass() == o.getClass()) { BankAccount ba = (BankAccount) o; return name.equals(ba.name) && balance == ba.balance && id == ba.id; } else { return false; } What's bad about the above? Hint: See Comparable API docs.Comparable API docs

7 The flaw BankAccount ba1 = new BankAccount("Jim", 123, 20.00); BankAccount ba2 = new BankAccount("Jim", 456, ); Set accounts = new TreeSet (); accounts.add(ba1); accounts.add(ba2); System.out.println(accounts); // [Jim($20.00)] Where did the other account go?  Since the two accounts are "equal" by the ordering of compareTo, the set thought they were duplicates and didn't store the second.

8 compareTo and equals compareTo should generally be consistent with equals.  a.compareTo(b) == 0 should imply that a.equals(b). from Comparable Java API docs: ... sorted sets (and sorted maps) without explicit comparators behave strangely when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.  For example, if one adds two keys a and b such that (!a.equals(b) && a.compareTo(b) == 0) to a sorted set that does not use an explicit comparator, the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.

9 What's the "natural" order? public class Rectangle implements Comparable { private int x, y, width, height; public int compareTo(Rectangle other) { //...? } } What is the "natural ordering" of rectangles?  By x, breaking ties by y?  By width, breaking ties by height?  By area? By perimeter? Do rectangles have any "natural" ordering?  Might we ever want to sort rectangles into some order anyway?

10 Comparator interface public interface Comparator { public int compare(T first, T second); } Interface Comparator is an external object that specifies a comparison function over some other type of objects.  Allows you to define multiple orderings for the same type.  Allows you to define a specific ordering for a type even if there is no obvious "natural" ordering for that type.

11 Comparator examples public class RectangleAreaComparator implements Comparator { // compare in ascending order by area (WxH) public int compare(Rectangle r1, Rectangle r2) { return r1.getArea() - r2.getArea(); } public class RectangleXYComparator implements Comparator { // compare by ascending x, break ties by y public int compare(Rectangle r1, Rectangle r2) { if (r1.getX() != r2.getX()) { return r1.getX() - r2.getX(); } else { return r1.getY() - r2.getY(); }

12 Using Comparators TreeSet and TreeMap can accept a Comparator parameter. Comparator comp = new RectangleAreaComparator(); Set set = new TreeSet (comp); Searching and sorting methods can accept Comparator s. Arrays.binarySearch( array, value, comparator ) Arrays.sort( array, comparator ) Collections.binarySearch( list, comparator ) Collections.max( collection, comparator ) Collections.min( collection, comparator ) Collections.sort( list, comparator ) Methods are provided to reverse a Comparator 's ordering: Collections.reverseOrder() Collections.reverseOrder( comparator )

13 Using compareTo compareTo can be used as a test in an if statement. String a = "alice"; String b = "bob"; if (a.compareTo(b) < 0) { // true... } PrimitivesObjects if (a < b) {...if (a.compareTo(b) < 0) {... if (a <= b) {...if (a.compareTo(b) <= 0) {... if (a == b) {...if (a.compareTo(b) == 0) {... if (a != b) {...if (a.compareTo(b) != 0) {... if (a >= b) {...if (a.compareTo(b) >= 0) {... if (a > b) {...if (a.compareTo(b) > 0) {...

14 compareTo tricks subtraction trick - Subtracting related numeric values produces the right result for what you want compareTo to return: // sort by x and break ties by y public int compareTo(Point other) { if (x != other.x) { return x - other.x; // different x } else { return y - other.y; // same x; compare 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  NOTE: This trick doesn't work for double s (but see Math.signum )

15 compareTo tricks 2 delegation trick - If your object's fields are comparable (such as strings), use their compareTo results to help you: // sort by employee name, e.g. "Jim" < "Susan" public int compareTo(Employee other) { return name.compareTo(other.getName()); } toString trick - If your object's toString representation is related to the ordering, use that to help you: // sort by date, e.g. "09/19" > "04/01" public int compareTo(Date other) { return toString().compareTo(other.toString()); }