Java HashMap clone() Method
The clone() method is used to copy a HashMap; it is a shallow copy.
Extension:
A shallow copy only copies the pointer to an object, not the object itself; the new and old objects still share the same block of memory, soif one of the objects changes this address, it will affect the other object..
The counterpart of a shallow copy is a deep copy; a deep copy completely copies an object out of memory, allocating a new area from the heap memory to store the new object, andmodifying the new object will not affect the original object.
The syntax of the clone() method is:
hashmap.clone()
**Note:** hashmap is an object of the HashMap class.
Parameter Description:
- None
Return Value
Returns a copy of the HashMap instance (object).
Example
The following example demonstrates the use of the clone() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
HashMap
<
Integer
, String
sites
=
new
HashMap
<>
(
)
;
sites.
put
(
1
,
"Google"
)
;
sites.
put
(
2
,
"Runoob"
)
;
sites.
put
(
3
,
"Taobao"
)
;
System
.
out
.
println
(
"HashMap: "
sites
)
;
// Copy sites
HashMap
<
Integer
, String
cloneSites
=
(
HashMap
<
Integer
, String
)
sites.
clone
(
)
;
System
.
out
.
println
(
"Cloned HashMap: "
cloneSites
)
;
}
}
The output of the above program is:
HashMap: {1=Google, 2=Runoob, 3=Taobao}
Cloned HashMap: {1=Google, 2=Runoob, 3=Taobao}
In the above example, we created a HashMap named sites, and then used the clone() method to make a copy of sites.
In the example above, we created a dynamic array named numbers.
(HashMap)sites.clone();
- sites.clone() - returns the copied sites object
- (HashMap
) casts the returned object to a HashMap whose key is of type Integer and values are of type String.
Return value of the clone() method:
Example
import
java.util.HashMap
;
class
Main
{
public
static
void
main
(
String
[
]
args
)
{
// Create a hashmap
HashMap
<
String
, Integer
primeNumbers
=
new
HashMap
<>
(
)
;
primeNumbers.
put
(
"Two"
,
2
)
;
primeNumbers.
put
(
"Three"
,
3
)
;
primeNumbers.
put
(
"Five"
,
5
)
;
System
.
out
.
println
(
"Numbers: "
primeNumbers
)
;
// Output the return value of the clone() method
System
.
out
.
println
(
"Return value of clone(): "
primeNumbers.
clone
(
)
)
;
}
}
The output of the above program is:
Prime Numbers: {Five=5, Two=2, Three=3}
Return value of clone(): {Five=5, Two=2, Three=3}
In the above example, we created a HashMap named primeNumbers, and the output is the return value of the clone() method.
**Note:** The clone() method is not specific to the HashMap class; any class that implements the Cloneable interface can use the clone() method.
Java HashMap