Java Reference
In-Depth Information
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 follow-
ing expressions are
true
.
n
instanceof
Integer
s
instanceof
String
d
instanceof
java.util.Date
n
instanceof
Object
s
instanceof
Object
d
instanceof
Object
n
instanceof
Comparable
s
instanceof
Comparable
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
inter-
face. Listing 13.8 gives an example of sorting an array of strings and an array of
BigInteger
objects.
L
ISTING
13.8
SortComparableObjects.java
1
import
java.math.*;
2
3
public class
SortComparableObjects {
4
public static void
main(String[] args) {
5 String[] cities = {
"Savannah"
,
"Boston"
,
"Atlanta"
,
"Tampa"
};
6 java.util.Arrays.sort(cities);
7
for
(String city: cities)
8 System.out.print(city +
" "
);
9 System.out.println();
10
11 BigInteger[] hugeNumbers = {
new
BigInteger(
"2323231092923992"
),
12
new
BigInteger(
"432232323239292"
),
13
new
BigInteger(
"54623239292"
)};
14 java.util.Arrays.sort(hugeNumbers);
15
for
(BigInteger number: hugeNumbers)
16 System.out.print(number +
" "
);
17 }
18 }
create an array
sort the array
create an array
sort the array
Search WWH ::
Custom Search