在 Java 中初始化 HashMap


HashMap 類使用散列表來實現 Map 介面。這使得即使對於大型集合,get( ) 和 put( ) 等基本操作的執行時間也能保持恆定。

以下是 HashMap 類支援的建構函式列表。

序號建構函式和說明
1HashMap( )
此建構函式構造一個預設的 HashMap。
2HashMap(Map m)
此建構函式使用給定 Map 物件 m 的元素初始化雜湊對映。
3HashMap(int capacity)
此建構函式將雜湊對映的容量初始化為給定的整數值,capacity。
4HashMap(int capacity, float fillRatio)
此建構函式使用其引數初始化雜湊對映的容量和填充率。

以下是一個示例,展示如何在 Java 中初始化和使用 HashMap −

示例

 線上演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      HashMap<Integer, String> hashMap = new HashMap<Integer, String>(7);
      hashMap.put(1, "Laptop");
      hashMap.put(2, "LCD");
      hashMap.put(3, "LED");
      hashMap.put(4, "Desktop");
      hashMap.put(5, "Laptop");
      hashMap.put(6, "Notebook");
      hashMap.put(7, "Mobile");
      System.out.println("HashMap = " + hashMap);
   }
}

輸出

HashMap = {1=Laptop, 2=LCD, 3=LED, 4=Desktop, 5=Laptop, 6=Notebook, 7=Mobile}

我們來看另一個示例 −

示例

 線上演示

import java.util.*;
public class Main {
   public static void main(String args[]) {
      HashMap hashMap = new HashMap();
      hashMap.put("John", new Integer(10000));
      hashMap.put("Tim", new Integer(25000));
      hashMap.put("Adam", new Integer(15000));
      hashMap.put("Katie", new Integer(30000));
      hashMap.put("Jacob", new Integer(45000));
      hashMap.put("Steve", new Integer(23000));
      hashMap.put("Nathan", new Integer(25000));
      hashMap.put("Amy", new Integer(27000));
      Set set = hashMap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry map = (Map.Entry)iterator.next();
         System.out.print(map.getKey() + ": ");
         System.out.println(map.getValue());
      }
      System.out.println();
      System.out.println("Size of IdentintyHashMap: "+hashMap.size());
      int bonus = ((Integer)hashMap.get("Amy")).intValue();
      hashMap.put("Amy", new Integer(bonus + 5000));
      System.out.println("Amy's salary after bonus = " + hashMap.get("Amy"));
      int deductions = ((Integer)hashMap.get("Steve")).intValue();
      hashMap.put("Steve", new Integer(deductions - 3000));
      System.out.println("Steve's salary after deductions = " + hashMap.get("Steve"));
   }
}

輸出

Adam: 15000
Nathan: 25000
Katie: 30000
Steve: 23000
John: 10000
Tim: 25000
Amy: 27000
Jacob: 45000
Size of IdentintyHashMap: 8
Amy's salary after bonus = 32000
Steve's salary after deductions = 20000

上次更新日期:20-Sep-2019

607 瀏覽量

開啟你的 職業生涯

完成課程可以獲得認證

開始
廣告