Java Reference
In-Depth Information
You can now use the
sort
method to sort an array of
ComparableRectangle
objects,
as in Listing 13.10.
L
ISTING
13.10
SortRectangles.java
1
public class
SortRectangles {
2
public static void
main(String[] args) {
3 ComparableRectangle[] rectangles = {
4
new
ComparableRectangle(
3.4
,
5.4
),
5
new
ComparableRectangle(
13.24
,
55.4
),
6
new
ComparableRectangle(
7.4
,
35.4
),
7
new
ComparableRectangle(
1.4
,
25.4
)};
8 java.util.Arrays.sort(rectangles);
9
for
(Rectangle rectangle: rectangles) {
10 System.out.print(rectangle +
" "
);
11 System.out.println();
12 }
13 }
14 }
create an array
sort the array
An interface provides another form of generic programming. It would be difficult to use a
generic
sort
method to sort the objects without using an interface in this example, because
Width: 3.4 Height: 5.4 Area: 18.36
Width: 1.4 Height: 25.4 Area: 35.559999999999995
Width: 7.4 Height: 35.4 Area: 261.96
Width: 13.24 Height: 55.4 Area: 733.496
benefits of interface
multiple inheritance would be necessary to inherit
Comparable
and another class, such as
Rectangle
, at the same time.
The
Object
class contains the
equals
method, which is intended for the subclasses of the
Object
class to override in order to compare whether the contents of the objects are the same.
Suppose that the
Object
class contains the
compareTo
method, as defined in the
Comparable
interface; the
sort
method can be used to compare a list of
any
objects. Whether a
compareTo
method should be included in the
Object
class is debatable. Since the
compareTo
method is
not defined in the
Object
class, the
Comparable
interface is defined in Java to enable objects
to be compared if they are instances of the
Comparable
interface. It is strongly recommended
(though not required) that
compareTo
should be consistent with
equals
. That is, for two
objects
o1
and
o2
,
o1.compareTo(o2) == 0
if and only if
o1.equals(o2)
is
true
.
13.17
✓
✓
True or false? If a class implements
Comparable
, the object of the class can invoke
the
compareTo
method.
Check
Point
13.18
Which of the following is the correct method header for the
compareTo
method in
the
String
class?
public int
compareTo(String o)
public int
compareTo(Object o)
13.19
Can the following code be compiled? Why?
Integer n1 =
new
Integer(
3
);
Object n2 =
new
Integer(
4
);
System.out.println(n1.compareTo(n2));
Search WWH ::
Custom Search