1. 程式人生 > >Hash Map 詳細解釋及示例

Hash Map 詳細解釋及示例

目錄

  • HashMap在java中的應用及示例
    • HashMap的內部結構
    • HashMap的效能
    • 同步HashMap
    • HashMap的建構函式
    • HashMap的時間複雜度
    • HashMap的方法
      • 1. void clear():用於從對映中刪除所有對映。
      • 2. boolean containsKey(key_element)查詢是否存在指定鍵的對映
      • 3. boolean containsValue(Object value):用於刪除對映中任何特定鍵的值
      • 4. Object clone():它用於返回上述雜湊對映的淺拷貝
      • 5. boolean isEmpty():用於返回雜湊對映的集合檢視
      • 6. Set entrySet():用於返回雜湊對映的Set檢視
      • 7. Object get(Object key):用於檢索或獲取由特定鍵對映的值
      • 8. Set ketSet():它用於返回鍵的集合檢視
      • 9. int size():它用於返回對映的大小
      • 10. Object put(Object key,Object value):用於將鍵值對的特定對映插入到對映中。
      • 11. putAll(Map M):它用於將一個對映中的所有元素複製到另一個對映中。
      • 12. Object remove(Object key):它用於刪除對映中任何特定鍵的值。
      • 13. Collection values():它用於返回HashMap中值的集合檢視。

HashMap在java中的應用及示例

HashMap自1.2起就是java集合的一部分,它提供了java基本的map對映介面實現。通過將資料儲存在(Key, Value)也就是鍵值對中。想要得到值就必須知道對應的鍵。之所以用 HashMap 命名是因為它使用了一個叫做 Hashing 的技術,Hashing 是一種可以將長字串轉換成短字串並且表示的字串相同。段字串的好處是更快的標記和索引。HashSet同樣偶爾使用HashMap,偶爾也會使用連結串列來儲存鍵值對。

幾個HashMap的重要屬性:

  • HashMap是java.util包的一部分
  • HashMap整合子抽象類AbstractMap,並且AbstractMap也提供一個不萬丈的Map介面實現。
  • 它同樣實現了可克隆和可序列化介面,K和V在之前的描述中分別代表Key和Value
  • HashMap不允許有重複的Keys但是允許有重複的Values,即一個單獨的key不能包含多個value,但不止一個key可以包含一個同樣的value。
  • HashMap允許唯一空Key但允許多個空Values
  • 這個類不保證對映的順序,它不能保證順序一直保持不變,它和HashTable大致相似,但是不同步。

HashMap的內部結構

HashMap的內在包含了一個節點陣列,其中一個節點可以表示成一個包含四個領域的類。

  1. int hash
  2. K key
  3. V value
  4. Node<K,V> next

Node包含了它自身物件的引用,所以這是一個連結串列。
HashMap:

HashMap的效能

  1. 初始容量(Initial Capacity)
  2. 負荷係數(Load Factor)
    • \(負荷係數 = \cfrac{表中儲存的元素的數量}{雜湊表的大小}\)
    • 示例:如果內部容量為16,負載係數為0.75,那麼當表中有12個元素時,bucket的數量將自動增加。

容量即容器的承載量,一旦HashMap被例項化即有了初始容量負荷係數使用來測量何時重新雜湊需要停止。重新雜湊是用來提升容量的步驟。在HashMap中容量是乘以2。負荷係數同樣是測量那些部分在重新雜湊之前允許被填入。當HashMap中的條目數增加了當前容量和負載因子的乘積時,就會增加容量,這時就進行了重新雜湊。如果初始容量持續增高那麼重新雜湊用不會停止,但是通過不斷的增高初始容量它增加了迭代的時間複雜度,所以他應該謹慎選擇來提升他的效能,當設定初始容量時應該將預計的values考慮在內。通常情況下負荷係數設定為0.75,它較好地平衡了時間和空間花費。負荷係數的value在0-1之間

同步HashMap

HashMap是非同步的也就是說多執行緒可以同時訪問。如果多執行緒同是訪問這個類而且至少有一個執行緒改變他的結構那麼就有必要讓他在外部同步。它是通過同步一些封裝了對映的物件來完成的。如果不存在這樣的物件,則可以將其封裝在Collections.synchronizedMap()中,以使HashMap同步,並避免意外的非同步訪問。
示例如下:

Map m = Collections.synchronizedMap(new HashMap(...));Map 

現在Map m是同步的了

如果在建立迭代器之後進行任何結構修改(除了通過迭代器的remove方法之外的任何方式),該類的迭代器都是快速失效的。在迭代器失敗時,它將丟擲ConcurrentModificationException。

HashMap的建構函式

HashMap提供了4個建構函式,每個的訪問修飾符都是公共的:

  1. HashMap():它是建立HashMap例項的預設建構函式,初始容量為16,負載係數為0.75。
  2. HashMap(int初始容量):它建立一個HashMap例項,該例項具有指定的初始容量和負載因子0.75。
  3. HashMap(int初始容量,float loadFactor):它建立一個HashMap例項,該例項具有指定的初始容量和指定的負載因子。
  4. HashMap(Map Map):它使用與指定對映相同的對映建立HashMap例項。

Example:

    // Java program to illustrate 
    // Java.util.HashMap 
  
    import java.util.HashMap; 
    import java.util.Map; 
    
    public class GFG { 
        public static void main(String[] args) 
        { 
  
        HashMap<String, Integer> map 
            = new HashMap<>(); 
  
        print(map); 
        map.put("vishal", 10); 
        map.put("sachin", 30); 
        map.put("vaibhav", 20); 
  
        System.out.println("Size of map is:-"+ map.size()); 
  
        print(map); 
        if (map.containsKey("vishal")) { 
            Integer a = map.get("vishal"); 
            System.out.println("value for key"+ " \"vishal\" is:- "+ a); 
        } 
  
        map.clear(); 
        print(map); 
    } 
  
    public static void print(Map<String, Integer> map) 
    { 
        if (map.isEmpty()) { 
            System.out.println("map is empty"); 
        } 
  
        else { 
            System.out.println(map); 
        } 
    } 
} 

輸出:

map is empty  
Size of map is:- 3  
{vaibhav=20, vishal=10, sachin=30}  
value for key "vishal" is:- 10  
map is empty

HashMap的時間複雜度

HashMap為基本操作提供了恆定的時間複雜度,如果正確編寫了雜湊函式,並且正確地將元素分散到各個buckets中,則使用get和put。遍歷所有的HashMap取決於HashMap的容量和許多鍵-值對。通常來說,它與容量+大小成正比。容量是HashMap中的buckets。所以一開始在HashMap中保留大量bucket不友好。

HashMap的方法

1. void clear():用於從對映中刪除所有對映。

  • 語法 Hash_Map.clear()
  • 引數:無引數
  • 返回值: 無返回值
  • 示例如下:
 //將字串對映成為整數鍵
 // Java code to illustrate the clear() 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, "pomelos"); 
         hash_map.put(15, "4"); 
         hash_map.put(20, "pomelos"); 
         hash_map.put(25, "Welcomes"); 
         hash_map.put(30, "You"); 
 
         // Displaying the HashMap 
         System.out.println("Initial Mappings are: " + hash_map); 
 
         // Clearing the hash map using clear() 
         hash_map.clear(); 
 
         // Displaying the final HashMap 
         System.out.println("Finally the maps look like this: " + hash_map); 
       } 
   } 

輸出:

Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
Finally the maps look like this: {}
//將整數對映成為字串
// Java code to illustrate the clear() 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("pomelos", 10); 
        hash_map.put("4", 15); 
        hash_map.put("pomelos", 20); 
        hash_map.put("Welcomes", 25); 
        hash_map.put("You", 30); 

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

        // Clearing the hash map using clear() 
        hash_map.clear(); 

        // Displaying the final HashMap 
        System.out.println("Finally the maps look like this: " + hash_map); 
    } 
} 

輸出:

Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
Finally the maps look like this: {}

2. boolean containsKey(key_element)查詢是否存在指定鍵的對映

  • 語法 Hash_Map.containsKey(key_element)
  • 引數: 只有key_element引數指向在對映中想要查詢的對映元素。
  • 返回值:返回值只有ture和false
  • 示例如下:
 //將字串對映為整數
 // Java code to illustrate the containsKey() 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, "pomelos"); 
     hash_map.put(15, "4"); 
     hash_map.put(20, "pomelos"); 
     hash_map.put(25, "Welcomes"); 
     hash_map.put(30, "You"); 

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

     // Checking for the key_element '20' 
     System.out.println("Is the key '20' present? " +  
     hash_map.containsKey(20)); 

     // Checking for the key_element '5' 
     System.out.println("Is the key '5' present? " +  
     hash_map.containsKey(5)); 
     } 
 } 

輸出:

Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
 Is the key '20' present? true
 Is the key '5' present? false
//將整數對映成為字串
// Java code to illustrate the containsKey() 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("pomelos", 10); 
     hash_map.put("4", 15); 
     hash_map.put("pomelos", 20); 
     hash_map.put("Welcomes", 25); 
     hash_map.put("You", 30); 

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

     // Checking for the key_element 'Welcomes' 
     System.out.println("Is the key 'Welcomes' present? " +  
     hash_map.containsKey("Welcomes")); 

     // Checking for the key_element 'World' 
     System.out.println("Is the key 'World' present? " +  
     hash_map.containsKey("World")); 
     } 
 } 

輸出:
Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25} Is the key 'Welcomes' present? true Is the key 'World' present? false

3. boolean containsValue(Object value):用於刪除對映中任何特定鍵的值

  • 語法:Hash_Map.containsValue(Object Value)
  • 引數: 該方法僅接受物件型別的一個引數值,並引用其對映應該由對映內的任何鍵進行檢查的值。
  • 返回值:如果檢測到值的對映,則該方法返回布林值true,其餘情況均為false。
  • 時間複雜度:O(n)
  • 示例如下:
// 將字串對映為整數
// Java code to illustrate the containsValue() 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, "pomelos"); 
     hash_map.put(15, "4"); 
     hash_map.put(20, "pomelos"); 
     hash_map.put(25, "Welcomes"); 
     hash_map.put(30, "You"); 

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

     // Checking for the Value 'pomelos' 
     System.out.println("Is the value 'pomelos' present? " +  
     hash_map.containsValue("pomelos")); 

     // Checking for the Value 'World' 
     System.out.println("Is the value 'World' present? " +  
     hash_map.containsValue("World")); 
     } 
 } 

輸出:

Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
 Is the value 'pomelos' present? true
 Is the value 'World' present? false
// 經整數對映為字串
// Java code to illustrate the containsValue() 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("pomelos", 10); 
     hash_map.put("4", 15); 
     hash_map.put("pomelos", 20); 
     hash_map.put("Welcomes", 25); 
     hash_map.put("You", 30); 

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

     // Checking for the Value '10' 
     System.out.println("Is the value '10' present? " + 
     hash_map.containsValue(10)); 

     // Checking for the Value '30' 
     System.out.println("Is the value '30' present? " + 
     hash_map.containsValue(30)); 

     // Checking for the Value '40' 
     System.out.println("Is the value '40' present? " +  
     hash_map.containsValue(40)); 
     } 
 } 

輸出:

 Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
 Is the value '10' present? false
 Is the value '30' present? true
 Is the value '40' present? false

4. Object clone():它用於返回上述雜湊對映的淺拷貝

  • 語法 Hash_Map.clone()
  • 引數: 無引數
  • 返回值:該方法只返回HashMap的一個副本
  • 示例如下:
  // 將字串對映為數字
  // 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      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=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The cloned map look like this: {25=Welcomes, 10=pomelos, 20=pomelos, 30=You, 15=4}
  // 將整數對映為字串
  // 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 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, pomelos=20, You=30, Welcomes=25}
  The cloned map look like this: {pomelos=20, 4=15, You=30, Welcomes=25}

5. boolean isEmpty():用於返回雜湊對映的集合檢視

  • 語法 Hash_Map.isEmpty()
  • 引數: 無引數
  • 返回值: 如果對映為空或不包含任何對映對,則該方法返回布林值true,反之則為false。
  • 示例如下:
  // 將整數對映成為字串
  // Java code to illustrate the isEmpty() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Checking for the emptiness of Map 
      System.out.println("Is the map empty? " + hash_map.isEmpty()); 
      } 
  } 

輸出:

  The Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  Is the map empty? false     
  // 對於空hashMap
  // Java code to illustrate the isEmpty() 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>(); 

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

      // Checking for the emptiness of Map 
      System.out.println("Is the map empty? " + hash_map.isEmpty()); 
      } 
  } 

輸出:

  The Mappings are: {}
  Is the map empty? true

6. Set entrySet():用於返回雜湊對映的Set檢視

  • 語法 hash_map.entrySet()
  • 引數:無引數
  • 返回值: 該方法返回與雜湊對映具有相同元素的集合。
  • 示例:
  // 字串對映成整數
  // Java code to illustrate the entrySet() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Using entrySet() to get the set view 
      System.out.println("The set is: " + hash_map.entrySet()); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The set is: [20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4]
// 講整數對映成為字串
// Java code to illustrate the entrySet() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Using entrySet() to get the set view 
      System.out.println("The set is: " + hash_map.entrySet()); 
      } 
  } 

輸出:

  Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  The set is: [4=15, pomelos=20, You=30, Welcomes=25]

7. Object get(Object key):用於檢索或獲取由特定鍵對映的值

  • 語法 hash_map.keySet()
  • 引數: 無需引數
  • 返回值: 該方法返回一個具有雜湊對映鍵的集合。
  • 示例如下:
// 將字串對映為整數值
// Java code to illustrate the keySet() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Using keySet() to get the set view of keys 
      System.out.println("The set is: " + hash_map.keySet()); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The set is: [20, 25, 10, 30, 15]
// 將整數對映成為字串
// Java code to illustrate the keySet() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Using keySet() to get the set view of keys 
      System.out.println("The set is: " + hash_map.keySet()); 
      } 
  } 

輸出:

  Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  The set is: [4, pomelos, You, Welcomes]

8. Set ketSet():它用於返回鍵的集合檢視

* 語法 hash_map.keySet()
* 引數: 無引數
* 返回值:該方法返回一個具有雜湊對映鍵的集合。
* 示例如下:
// 將字串對映為整數
// Java code to illustrate the keySet() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Using keySet() to get the set view of keys 
      System.out.println("The set is: " + hash_map.keySet()); 
  } 
} 

輸出:

    Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
    The set is: [20, 25, 10, 30, 15]
//將整數對映為字串
// Java code to illustrate the keySet() 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("pomelos", 10); 
        hash_map.put("4", 15); 
        hash_map.put("pomelos", 20); 
        hash_map.put("Welcomes", 25); 
        hash_map.put("You", 30); 
  
        // Displaying the HashMap 
        System.out.println("Initial Mappings are: " + hash_map); 
  
        // Using keySet() to get the set view of keys 
        System.out.println("The set is: " + hash_map.keySet()); 
    } 
} 

輸出:

    Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
    The set is: [4, pomelos, You, Welcomes]

9. int size():它用於返回對映的大小

* 語法: Hash_Map.size()
* 引數: 無需引數
* 返回值: 該方法返回對映的大小,這也表示對映中存在的鍵值對的數量。
* 示例如下
//將字串對映成為整數
// Java code to illustrate the size() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Displaying the size of the map 
      System.out.println("The size of the map is " + hash_map.size()); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The size of the map is 5
  // 將整數對映成為字串
  // Java code to illustrate the size() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Displaying the size of the map 
      System.out.println("The size of the map is " + hash_map.size()); 
      } 
  } 

輸出:

  Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  The size of the map is 4

10. Object put(Object key,Object value):用於將鍵值對的特定對映插入到對映中。

  • 語法 Hash_Map.put(key, value)
  • 引數: 該方法有兩個引數,都是HashMap的物件型別。
    • key: This refers to the key element that needs to be inserted into the Map for mapping.
    • value: This refers to the value that the above key would map into.
  • 返回值: 如果傳遞了現有的鍵,則返回以前的值。如果傳遞了一個新對,則返回NULL。
  • 示例如下:
// 當傳遞一個存在key
// Java code to illustrate the put() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Inserting existing key along with new value 
      String returned_value = (String)hash_map.put(20, "All"); 

      // Verifying the returned value 
      System.out.println("Returned value is: " + returned_value); 

      // Displayin the new map 
      System.out.println("New map is: " + hash_map); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  Returned value is: pomelos
  New map is: {20=All, 25=Welcomes, 10=pomelos, 30=You, 15=4}
// 當傳遞一個新值
// Java code to illustrate the put() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 

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

      // Inserting existing key along with new value 
      String returned_value = (String)hash_map.put(50, "All"); 

      // Verifying the returned value 
      System.out.println("Returned value is: " + returned_value); 

      // Displayin the new map 
      System.out.println("New map is: " + hash_map); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  Returned value is: null
  New map is: {50=All, 20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}

11. putAll(Map M):它用於將一個對映中的所有元素複製到另一個對映中。

  • 語法 new_hash_map.putAll(exist_hash_map)
  • 引數:該方法接受一個引數exist_hash_map,該引數引用我們想要複製的現有對映。
  • 返回值: 無返回值
  • 異常:如果我們想要複製的對映是NULL,這個方法會丟擲 NullPointerException。
  • 示例如下:
      // 將字串對映為整數
      // Java code to illustrate the putAll() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 
  
      // Displaying the HashMap 
      System.out.println("Initial Mappings are: " + hash_map); 
  
      // Creating a new hash map and copying 
      HashMap<Integer, String> new_hash_map = new HashMap<Integer, String>(); 
      new_hash_map.putAll(hash_map); 
  
      // Displaying the final HashMap 
      System.out.println("The new map looks like this: " + new_hash_map); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The new map looks like this: {25=Welcomes, 10=pomelos, 20=pomelos, 30=You, 15=4}
// 將整數對映成為字串
// Java code to illustrate the putAll() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Creating a new hash map and copying 
      HashMap<String, Integer> new_hash_map = new HashMap<String, Integer>(); 
      new_hash_map.putAll(hash_map); 

      // Displaying the final HashMap 
      System.out.println("The new map looks like this: " + new_hash_map); 
      } 
  } 

輸出:

  Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  The new map looks like this: {pomelos=20, 4=15, You=30, Welcomes=25}

12. Object remove(Object key):它用於刪除對映中任何特定鍵的值。

  • 語法 Hash_Map.remove(Object key)
  • 引數: 該方法採用一個要從對映中刪除其對映的引數鍵。
  • 返回值:如果鍵存在,該方法將返回先前對映到指定鍵的值,否則將返回NULL。
  • 示例如下:
  // 當傳遞一個已存在key
  // Java code to illustrate the remove() 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, "pomelos"); 
      hash_map.put(15, "4"); 
      hash_map.put(20, "pomelos"); 
      hash_map.put(25, "Welcomes"); 
      hash_map.put(30, "You"); 
  
      // Displaying the HashMap 
      System.out.println("Initial Mappings are: " + hash_map);  
  
      // Removing the existing key mapping 
      String returned_value = (String)hash_map.remove(20); 
  
      // Verifying the returned value 
      System.out.println("Returned value is: "+ returned_value); 
  
      // Displayin the new map 
      System.out.println("New map is: "+ hash_map); 
      } 
  } 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  Returned value is: pomelos
  New map is: {25=Welcomes, 10=pomelos, 30=You, 15=4}
// 當傳遞一個新key
// Java code to illustrate the remove() 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, "pomelos"); 
    hash_map.put(15, "4"); 
    hash_map.put(20, "pomelos"); 
    hash_map.put(25, "Welcomes"); 
    hash_map.put(30, "You"); 
 
    // Displaying the HashMap 
    System.out.println("Initial Mappings are: " + hash_map);  
 
    // Removing the new key mapping 
    String returned_value = (String)hash_map.remove(50); 
 
    // Verifying the returned value 
    System.out.println("Returned value is: "+ returned_value); 
 
    // Displayin the new map 
    System.out.println("New map is: "+ hash_map); 
 } 
} 

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 3`0=You, 15=4}
  Returned value is: null
  New map is: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}

13. Collection values():它用於返回HashMap中值的集合檢視。

  • 語法 Hash_Map.values()
  • 引數:無引數
  • 返回值:該方法用於返回包含對映的所有值的集合檢視。
  • 示例如下:
  // 將字串對映為整數
  // Java code to illustrate the values() 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, "pomelos"); 
          hash_map.put(15, "4"); 
          hash_map.put(20, "pomelos"); 
          hash_map.put(25, "Welcomes"); 
          hash_map.put(30, "You"); 
  
          // Displaying the HashMap 
          System.out.println("Initial Mappings are: " + hash_map); 
  
          // Using values() to get the set view of values 
          System.out.println("The collection is: " + hash_map.values()); 
      } 
  }   

輸出:

  Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  The collection is: [pomelos, Welcomes, pomelos, You, 4]
// 將整數對映成字串
// Java code to illustrate the values() 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("pomelos", 10); 
      hash_map.put("4", 15); 
      hash_map.put("pomelos", 20); 
      hash_map.put("Welcomes", 25); 
      hash_map.put("You", 30); 

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

      // Using values() to get the set view of values 
      System.out.println("The collection is: " + hash_map.values()); 
  } 
} 

輸出:

  Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  The collection is: [15, 20, 30, 25]

參考文獻:

https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html
https://www.geeksforgeeks.org/hashset-in-java/