Java Reference
In-Depth Information
12
new
BigInteger(
"432232323239292"
),
13
new
BigInteger(
"54623239292"
)};
14
15
for
(BigInteger number: hugeNumbers)
16 System.out.print(number +
" "
);
17 }
18 }
java.util.Arrays.sort(hugeNumbers);
sort the array
Atlanta Boston Savannah Tampa
54623239292 432232323239292 2323231092923992
The program creates an array of strings (line 5) and invokes the
sort
method to sort the
strings (line 6). The program creates an array of
BigInteger
objects (lines 11-13) and
invokes the
sort
method to sort the
BigInteger
objects (line 14).
You cannot use the
sort
method to sort an array of
Rectangle
objects, because
Rectangle
does not implement
Comparable
. However, you can define a new rectangle
class that implements
Comparable
. The instances of this new class are comparable. Let this
new class be named
ComparableRectangle
, as shown in Listing 15.9.
L
ISTING
15.9
ComparableRectangle.java
1
public class
ComparableRectangle
extends
Rectangle
2
implements
Comparable<ComparableRectangle>
{
implements
Comparable
3
/** Construct a ComparableRectangle with specified properties */
4
public
ComparableRectangle(
double
width,
double
height) {
5
super
(width, height);
6 }
7
8 @Override
// Implement the compareTo method defined in Comparable
9
public int
compareTo(ComparableRectangle o)
{
implement
compareTo
10
if
(getArea() > o.getArea())
11
return
1
;
12
else if
(getArea() < o.getArea())
13
return
-1
;
14
else
15
return
0
;
16 }
17
18 @Override
// Implement the toString method in GeometricObject
19
public
String toString() {
implement
toString
20
return super
.toString() +
" Area: "
+ getArea();
21 }
22 }
ComparableRectangle
extends
Rectangle
and implements
Comparable
, as shown in
Figure 15.5. The keyword
implements
indicates that
ComparableRectangle
inherits all
the constants from the
Comparable
interface and implements the methods in the interface.
The
compareTo
method compares the areas of two rectangles. An instance of
ComparableRectangle
is also an instance of
Rectangle
,
GeometricObject
,
Object
,
and
Comparable
.
You can now use the
sort
method to sort an array of
ComparableRectangle
objects, as
in Listing 15.10.