Java HashMap clone()方法
让我们把java中浅层复制和深层复制的基础概念弄清楚。浅层复制是比较快的。然而,它是 “懒惰的”,它处理指针和引用。它不是为指针所指向的特定知识创建一个当代副本,而是简单地复制指针的价格。因此,每个第一份和因此的副本都可以有引用恒定基础知识的指针。在另一个方面,深度复制或深度重复真正克隆了基础数据。它不在第一个和因此的副本之间共享。
java.util.HashMap.clone()方法存在于java.util包中,通常用于返回上述哈希图的浅层副本。它只是创建一个Map的副本。
语法
Hash_Map.clone()
参数: 该方法不接受任何参数。
返回值: 该方法只是返回HashMap的一个副本。
例1 :
// Java Program to Illustrate the clone() Method by
// Mapping String Values to Integer Keys
// Importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashMap
HashMap<Integer, String> hash_map
= new HashMap<Integer, String>();
// Mapping string values to int keys
// Using put() method
// Custom input values passed as arguments
hash_map.put(10, "Geeks");
hash_map.put(15, "4");
hash_map.put(20, "Geeks");
hash_map.put(25, "Welcomes");
hash_map.put(30, "You");
// Print and display the HashMap
System.out.println("Initial Mappings are: "
+ hash_map);
// Print and display the cloned HashMap
// using clone() method
System.out.println("The cloned map look like this: "
+ hash_map.clone());
}
}
输出
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
The cloned map look like this: {25=Welcomes, 10=Geeks, 20=Geeks, 30=You, 15=4}
例2 :
// Java code to illustrate the clone() method by
// Mapping Integer Values to String Keys
// Importing utility classes
import java.util.*;
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Creating an empty HashMap
// Declaring objects of type integer and string
HashMap<String, Integer> hash_map
= new HashMap<String, Integer>();
// Mapping int values to string keys
// using put() method
hash_map.put("Geeks", 10);
hash_map.put("4", 15);
hash_map.put("Geeks", 20);
hash_map.put("Welcomes", 25);
hash_map.put("You", 30);
// Print and display the HashMap
System.out.println("Initial Mappings are: "
+ hash_map);
// Print and display the cloned HashMap
// using clone() method
System.out.println("The cloned map look like this: "
+ hash_map.clone());
}
}
输出
Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}
The cloned map look like this: {Geeks=20, 4=15, You=30, Welcomes=25}
注意
- 同样的操作可以通过不同数据类型的变化和组合对任何类型的映射进行操作。
- clone()方法做的是浅层拷贝。但是在这里,由于使用了原始数据类型,原始哈希图和克隆哈希图中的值将不会相互影响。