java.util.HashMap.clone()方法用于返回所提到的哈希映射HashMap的浅表副本。它只是创建了map的副本。

HashMap.clone句法:

Hash_Map.clone()

参数:该方法不接受任何参数。

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

下面的程序用于说明java.util.HashMap.clone()的工作方法:
HashMap.clone程序1:将字符串值映射到整数键。

// Java code to illustrate the clone() method
import java.util.*;

public class Hash_Map_Demo {
    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
        hash_map.put(10, "breakyizhan");
        hash_map.put(15, "4");
        hash_map.put(20, "breakyizhan");
        hash_map.put(25, "Welcomes");
        hash_map.put(30, "You");

        // Displaying the HashMap
        System.out.println("Initial Mappings are: " + hash_map);

        // Displaying the cloned HashMap using clone()
        System.out.println("The cloned map look like this: " + hash_map.clone());
    }
}

输出:

Initial Mappings are: {20=breakyizhan, 25=Welcomes, 10=breakyizhan, 30=You, 15=4}
The cloned map look like this: {25=breakyizhan, 10=breakyizhan, 20=breakyizhan, 30=You, 15=4}

HashMap.clone程序2:将 整数值映射到字符串键。

// Java code to illustrate the clone() method
import java.util.*;

public class Hash_Map_Demo {
    public static void main(String[] args)
    {

        // Creating an empty HashMap
        HashMap<String, Integer> hash_map = new HashMap<String, Integer>();

        // Mapping int values to string keys
        hash_map.put("breakyizhan", 10);
        hash_map.put("4", 15);
        hash_map.put("breakyizhan", 20);
        hash_map.put("Welcomes", 25);
        hash_map.put("You", 30);

        // Displaying the HashMap
        System.out.println("Initial Mappings are: " + hash_map);

        // Displaying the cloned HashMap using clone()
        System.out.println("The cloned map look like this: " + hash_map.clone());
    }
}

输出:

Initial Mappings are: {4=15, breakyizhan=20, You=30, Welcomes=25}
The cloned map look like this: {breakyizhan=20, 4=15, You=30, Welcomes=25}

注意:对于具有不同数据类型的变体和组合的任何类型的映射,都可以执行相同的操作。

 
转载请保留页面地址:https://www.breakyizhan.com/java/5435.html
扫描二维码添加微信 
  • ,每次淘宝领取淘宝优惠券,淘宝购物更优惠。现在添加微信,还可以领取机械键盘50元优惠券!添加微信后回复机械键盘即可领取!
    支持我们,就用微信淘宝!