
The standard way for a Java class to define a comparison function for its objects is to define a compareTo method. Example: in the String class, there is a method: public int compareTo(String other)
To define multiple ways to compare objects, define distinct classes that implement Comparator and define a compare(T left, T right) method. This way comparator objects can be created and sent two …
- [PDF]
Chapter 12
The compareTo method has been shown to compare two String objects to see if one was less than, greater than, or equal to another. This section introduces a general way to compare any objects with …
- [PDF]
compareTo
compareTo() Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. Throws …
Approach 1: If a type T implements Comparable, exploit its natural ordering and use compareTo(). That is, to compare x with y, invoke x.compareTo(y). For example, to sort Strings instead of ints, we can …
- [PDF]
Lecture15 - Pomona
Comparable Interface with a single method that we need to implement: public int compareTo(T that) Implement it so that v.compareTo(w): Returns >0 if v is greater than w. Returns <0 if v is smaller than …
Comparable Interface (Note: this is Java 1.4.2 – Java 5.0 has generics) x.compareTo(y) returns a negative, zero, or positive integer based on whether x is less-than, equal-to, or greater-than y, …