Java Reference
In-Depth Information
13.20
You can define the
compareTo
method in a class without implementing the
Comparable
interface. What are the benefits of implementing the
Comparable
interface?
13.21
What is wrong in the following code?
public class
Test {
public static void
main(String[] args) {
Person[] persons = {
new
Person(
3
),
new
Person(
4
),
new
Person(
1
)};
java.util.Arrays.sort(persons);
}
}
class
Person {
private int
id;
Person(
int
id) {
this
.id = id;
}
}
Key
Point
Often it is desirable to create a copy of an object. To do this, you need to use the
clone
method and understand the
Cloneable
interface.
An interface contains constants and abstract methods, but the
Cloneable
interface is a
special case. The
Cloneable
interface in the
java.lang
package is defined as follows:
package
java.lang;
java.lang.Cloneable
public interface
Cloneable {
}
This interface is empty. An interface with an empty body is referred to as a
marker interface
.
A marker interface does not contain constants or methods. It is used to denote that a class
possesses certain desirable properties. A class that implements the
Cloneable
interface is
marked cloneable, and its objects can be cloned using the
clone()
method defined in the
Object
class.
Many classes in the Java library (e.g.,
Date
,
Calendar
, and
ArrayList
) implement
Cloneable
. Thus, the instances of these classes can be cloned. For example, the following code
marker interface
1 Calendar calendar =
new
GregorianCalendar(
2013
,
2
,
1
);
2 Calendar calendar1 = calendar;
3 Calendar calendar2 = (Calendar)calendar.clone();
4 System.out.println(
"calendar == calendar1 is "
+
5 (calendar == calendar1));
6 System.out.println(
"calendar == calendar2 is "
+
7 (calendar == calendar2));
8 System.out.println(
"calendar.equals(calendar2) is "
+
9 calendar.equals(calendar2));
displays
calendar == calendar1 is
true
calendar == calendar2 is
false
calendar.equals(calendar2) is
true
Search WWH ::
Custom Search