Java中的HashMap clone()方法

让我们明确一下基础概念。 java中的浅拷贝和深拷贝 .肤浅的重复更快。然而,它是“懒惰的”,它处理指针和引用。它没有创建指针指向的特定知识的当代副本,而是简单地复制指针价格。因此,每一个都是第一个,因此副本可以有引用常量基础知识的指针。另一方面,深度复制或深度重复确实克隆了底层数据。它不会在第一个用户和副本之间共享。

null

爪哇。util。HashMap。clone()方法存在于java内部。util包,通常用于返回上述哈希映射的浅层副本。它只是创建了地图的副本。

图片[1]-Java中的HashMap clone()方法-yiteyi-C++库

语法:

Hash_Map.clone()

参数: 该方法不采用任何参数。

返回值: 该方法只返回HashMap的一个副本。

例1:

JAVA

// 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

// 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()方法执行浅层复制。但在这里,原始和克隆hashmap中的值不会相互影响,因为使用的是原始数据类型。
© 版权声明
THE END
喜欢就支持一下吧
点赞8 分享