Java HashMap size() 方法



描述

Java HashMap size() 方法用於返回此對映中的鍵值對映數。

宣告

以下是 java.util.HashMap.size() 方法的宣告。

public int size()

引數

返回值

方法呼叫返回此對映中的鍵值對映數。

異常

獲取整數、整數對 HashMap 大小的示例

以下示例演示瞭如何使用 Java HashMap size() 方法獲取 Map 的大小。我們建立了一個 Integer,Integer 對的 Map 物件。然後添加了一些條目,列印了 map。使用 size() 方法檢索並列印 map 的大小。

package com.tutorialspoint;

import java.util.HashMap;

public class HashMapDemo {
   public static void main(String args[]) {
      
      // create hash map
      HashMap<Integer,Integer> newmap = new HashMap<>();

      // populate hash map
      newmap.put(1, 1);
      newmap.put(2, 2);
      newmap.put(3, 3); 

      System.out.println("Initial map elements: " + newmap);

      System.out.println("Size of the map: " + newmap.size());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Initial map elements: {1=1, 2=2, 3=3}
Size of the map: 3

獲取整數、字串對 HashMap 大小的示例

以下示例演示瞭如何使用 Java HashMap size() 方法獲取 Map 的大小。我們建立了一個 Integer,String 對的 Map 物件。然後添加了一些條目,列印了 map。使用 size() 方法檢索並列印 map 的大小。

package com.tutorialspoint;

import java.util.HashMap;

public class HashMapDemo {
   public static void main(String args[]) {
      
      // create hash map
      HashMap<Integer,String> newmap = new HashMap<>();

      // populate hash map
      newmap.put(1, "tutorials");
      newmap.put(2, "point");
      newmap.put(3, "is best"); 

      System.out.println("Initial map elements: " + newmap);

      System.out.println("Size of the map: " + newmap.size());
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Initial map elements: {1=tutorials, 2=point, 3=is best}
Size of the map: 3

獲取整數、學生對 HashMap 大小的示例

以下示例演示瞭如何使用 Java HashMap size() 方法獲取 Map 的大小。我們建立了一個 Integer,Student 對的 Map 物件。然後添加了一些條目,列印了 map。使用 size() 方法檢索並列印 map 的大小。

package com.tutorialspoint;

import java.util.HashMap;

public class HashMapDemo {
   public static void main(String args[]) {
      
      // create hash map
      HashMap<Integer,Student> newmap = new HashMap<>();

      // populate hash map
      newmap.put(1, new Student(1, "Julie"));
      newmap.put(2, new Student(2, "Robert"));
      newmap.put(3, new Student(3, "Adam"));

      System.out.println("Initial map elements: " + newmap);

      System.out.println("Size of the map: " + newmap.size());
   }
}
class Student {
   int rollNo;
   String name;

   Student(int rollNo, String name){
      this.rollNo = rollNo;
      this.name = name;
   }

   @Override
   public String toString() {
      return "[ " + this.rollNo + ", " + this.name + " ]";
   }
}

輸出

讓我們編譯並執行上述程式,這將產生以下結果。

Initial map elements: {1=[ 1, Julie ], 2=[ 2, Robert ], 3=[ 3, Adam ]}
Size of the map: 3
java_util_hashmap.htm
廣告
© . All rights reserved.