structure
Class NaturalComparator
java.lang.Object
|
+--structure.NaturalComparator
- All Implemented Interfaces:
- Comparator
- public class NaturalComparator
- extends Object
- implements Comparator
Implementation of the Comparator
interface that
provides a compare(java.lang.Object, java.lang.Object)
method that compares two objects using those
objects default compareTo methods.
Example usage:
To print out the equality relationship between two randomly generated integers
we could use the following:
public static void main(String[] argv){
Random rand = new Random();
Comparator c = new NaturalComparator()
;
//generate two random Integers
Integer a = new Integer(rand.nextInt(100));
Integer b = new Integer(rand.nextInt(100));
//print out the proper equality relationship between these integers
if(c.compare(a,b)
> 0) System.out.println("A:" + a + " > B:" + b);
else if (c.compare(a,b) < 0) System.out.println("A:" + a + " < B:" + b);
else System.out.println("A:" + a + " = B:" + b);
Method Summary |
int |
compare(Object a,
Object b)
Compare two values, a and b. |
boolean |
equals(Object b)
Returns true if the other object is a NaturalComparator. |
Methods inherited from class java.lang.Object |
, clone, finalize, getClass, hashCode, notify, notifyAll, registerNatives, toString, wait, wait, wait |
NaturalComparator
public NaturalComparator()
compare
public int compare(Object a,
Object b)
- Compare two values, a and b. Simply calls the default
compareTo method for a on b.
- Specified by:
compare
in interface Comparator
- Parameters:
a
- object performing the compareb
- the object being compared- Precondition:
- a, b non-null, and b is same type as a
- Postcondition:
- returns value <, ==, > 0 if a <, ==, > b
- Returns:
- value <, ==, > 0 if a <, ==, > b using a.compareTo
equals
public boolean equals(Object b)
- Returns true if the other object is a NaturalComparator.
- Specified by:
equals
in interface Comparator
- Overrides:
equals
in class Object
- Parameters:
b
- a possible NaturalComparator- Postcondition:
- returns true if b is a NaturalComparator
- Returns:
- true if b is a NaturalComparator