Java Reference
In-Depth Information
public class String extends Object
public class Date extends Object
implements Comparable<String>
implements Comparable<Date>
{
{
// class body omitted
// class body omitted
@Override
public int compareTo(String o) {
// Implementation omitted
@Override
public int compareTo(Date o) {
// Implementation omitted
}
}
}
}
Thus, numbers are comparable, strings are comparable, and so are dates. You can use the
compareTo method to compare two numbers, two strings, and two dates. For example, the
following code
1 System.out.println( new Integer( 3 ).compareTo( new Integer( 5 )));
2 System.out.println( "ABC" .compareTo( "ABE" ));
3 java.util.Date date1 = new java.util.Date( 2013 , 1 , 1 );
4 java.util.Date date2 = new java.util.Date( 2012 , 1 , 1 );
5 System.out.println(date1.compareTo(date2));
displays
-1
-2
1
Line 1 displays a negative value since 3 is less than 5 . Line 2 displays a negative value since
ABC is less than ABE . Line 5 displays a positive value since date1 is greater than date2 .
Let n be an Integer object, s be a String object, and d be a Date object. All the fol-
lowing expressions are true .
n instanceof Integer
n instanceof Object
n instanceof Comparable
s instanceof String
s instanceof Object
s instanceof Comparable
d instanceof java.util.Date
d instanceof Object
d instanceof Comparable
Since all Comparable objects have the compareTo method, the
java.util.Arrays.sort(Object[]) method in the Java API uses the compareTo
method to compare and sorts the objects in an array, provided that the objects are instances of
the Comparable interface. Listing 15.8 gives an example of sorting an array of strings and an
array of BigInteger objects.
L ISTING 15.8 SortComparableObjects.java
1 import java.math.*;
2
3 public class SortComparableObjects {
4
public static void main(String[] args) {
5
6
7 for (String city: cities)
8 System.out.print(city + " " );
9 System.out.println();
10
11
String[] cities = { "Savannah" , "Boston" , "Atlanta" , "Tampa" };
create an array
sort the array
java.util.Arrays.sort(cities);
BigInteger[] hugeNumbers = { new BigInteger( "2323231092923992" )
,
create an array
 
Search WWH ::




Custom Search