天天看點

java map clone_Java中HashMap的clone()方法: java.util.HashMap.clone() - Break易站

Java中的HashMap

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 hash_map = new HashMap();

// 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 hash_map = new HashMap();

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

注意:對于具有不同資料類型的變體群組合的任何類型的映射,都可以執行相同的操作。