Java Reference
In-Depth Information
In the preceding code, line 2 copies the reference of
calendar
to
calendar1
, so
calendar
and
calendar1
point to the same
Calendar
object. Line 3 creates a new object that is the
clone of
calendar
and assigns the new object's reference to
calendar2
.
calendar2
and
calendar
are different objects with the same contents.
The following code
1 ArrayList<Double> list1 =
new
ArrayList<>();
2 list1.add(
1.5
);
3 list1.add(
2.5
);
4 list1.add(
3.5
);
5 ArrayList<Double> list2 = (ArrayList<Double>)list1.clone();
6 ArrayList<Double> list3 = list1;
7 list2.add(
4.5
);
8 list3.remove(
1.5
);
9 System.out.println(
"list1 is "
+ list1);
10 System.out.println(
"list2 is "
+ list2);
11 System.out.println(
"list3 is "
+ list3);
displays
list1 is [2.5, 3.5]
list2 is [1.5, 2.5, 3.5, 4.5]
list3 is [2.5, 3.5]
In the preceding code, line 5 creates a new object that is the clone of
list1
and assigns the
new object's reference to
list2
.
list2
and
list1
are different objects with the same con-
tents. Line 6 copies the reference of
list1
to
list3
, so
list1
and
list3
point to the same
ArrayList
object. Line 7 adds
4.5
into
list2
. Line 8 removes
1.5
from
list3
. Since
list1
and
list3
point to the same
ArrayList
, line 9 and 11 display the same content.
You can clone an array using the
clone
method. For example, the following code
clone arrays
1
int
[] list1 = {
1
,
2
};
2
int
[] list2 = list1.clone();
3 list1[
0
] =
7
;
4 list2[
1
] =
8
;
5 System.out.println(
"list1 is "
+ list1[
0
] +
", "
+ list1[
1
]);
6 System.out.println(
"list2 is "
+ list2[
0
] +
", "
+ list2[
1
]);
displays
list1 is
7
,
2
list2 is
1
,
8
To define a custom class that implements the
Cloneable
interface, the class must override
the
clone()
method in the
Object
class. Listing 13.11 defines a class named
House
that
implements
Cloneable
and
Comparable
.
how to implement
Cloneable
L
ISTING
13.11
House.java
1
public class
House
implements
Cloneable, Comparable<House> {
2
private int
id;
3
private double
area;
4
private
java.util.Date whenBuilt;
5
6
public
House(
int
id,
double
area) {
7
this
.id = id;
8
this
.area = area;
9 whenBuilt =
new
java.util.Date();
10 }
Search WWH ::
Custom Search