Lecture 18: Comparable / Graph: 4/22


DJW section 6.1

Defining comparison operators for your own classes.

Code to define the comparison operator on strings to be just a comparison of their lengths.


Now any method that is defined to work over Comparables will work over MyStrings, such as Comparables.sort

Note we have also redefined "hashCode", so any method that uses hashTables will also work, though in this case "work" is a little odd.

Defining a method that works over Comparables

Code for an ordered list of some comparable type

GOrderedListA.java But this will not work with extension MyStringX of MyString MyStringX.java

You have to use instead GOrderedList.java

Conditions that have to be met.

Equals has to be an equivalence relation. Then equals divides the objects in the class into equivalence classes (different sense of class). If two object are in the same equivalence class, they are equal. If they are in different equivalence classes they are not equal.

compareTo has to be a total ordering compatable with equals

hashfun has to be compatable with equals.