Java Reference
In-Depth Information
13.16
Show the error in the following code:
interface
A {
void
m1();
}
class
B
implements
A {
void
m1() {
System.out.println(
"m1"
);
}
}
The
Comparable
interface defines the
compareTo
method for comparing objects.
Key
Point
Suppose you want to design a generic method to find the larger of two objects of the same
type, such as two students, two dates, two circles, two rectangles, or two squares. In order to
accomplish this, the two objects must be comparable, so the common behavior for the objects
must be comparable. Java provides the
Comparable
interface for this purpose. The interface
is defined as follows:
// Interface for comparing objects, defined in java.lang
package
java.lang;
java.lang.Comparable
public interface
Comparable<E> {
public int
compareTo(E o);
}
The
compareTo
method determines the order of this object with the specified object
o
and
returns a negative integer, zero, or a positive integer if this object is less than, equal to, or
greater than
o
.
The
Comparable
interface is a generic interface. The generic type
E
is replaced by a
concrete type when implementing this interface. Many classes in the Java library implement
Comparable
to define a natural order for objects. The classes
Byte
,
Short
,
Integer
,
Long
,
Float
,
Double
,
Character
,
BigInteger
,
BigDecimal
,
Calendar
,
String
, and
Date
all implement the
Comparable
interface. For example, the
Integer
,
BigInteger
,
String
,
and
Date
classes are defined as follows in the Java API:
public class
Integer
extends
Number
implements
Comparable<Integer> {
// class body omitted
public class
BigInteger
extends
Number
implements
Comparable<BigInteger> {
// class body omitted
@Override
public int
compareTo(Integer o) {
// Implementation omitted
@Override
public int
compareTo(BigInteger o) {
// Implementation omitted
}
}
}
}
public class
String
extends
Object
implements
Comparable<String> {
// class body omitted
public class
Date
extends
Object
implements
Comparable<Date> {
// class body omitted
@Override
public int
compareTo(String o) {
// Implementation omitted
@Override
public int
compareTo(Date o) {
// Implementation omitted
}
}
}
}
Search WWH ::
Custom Search