Java IdentityHashMap size() 方法



描述

Java IdentityHashMap size() 方法用於獲取此身份雜湊對映中的鍵值對映數量。

宣告

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

public int size()

引數

返回值

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

異常

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

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

package com.tutorialspoint;

import java.util.IdentityHashMap;

public class IdentityHashMapDemo {
   public static void main(String args[]) {
      
      // create identity map
      IdentityHashMap<Integer,Integer> newmap = new IdentityHashMap<>();

      // populate identity 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: {2=2, 3=3, 1=1}
Size of the map: 3

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

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

package com.tutorialspoint;

import java.util.IdentityHashMap;

public class IdentityHashMapDemo {
   public static void main(String args[]) {
      
      // create identity map
      IdentityHashMap<Integer,String> newmap = new IdentityHashMap<>();

      // populate identity 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: {2=point, 3=is best, 1=tutorials}
Size of the map: 3

獲取整數、物件對 IdentityHashMap 的大小示例

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

package com.tutorialspoint;

import java.util.IdentityHashMap;

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

      // populate identity 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 ], 3=[ 3, Adam ], 2=[ 2, Robert ]}
Size of the map: 3
java_util_identityhashmap.htm
廣告