Java IdentityHashMap get() 方法



描述

Java IdentityHashMap get(Object key) 方法用於獲取此身份雜湊對映中指定鍵所對映到的值,如果對映不包含此鍵的對映,則返回 null。

宣告

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

public V get(Object key)

引數

key − 這是要返回其關聯值的鍵。

返回值

方法呼叫如果此對映對映到指定鍵的值,則返回“true”,如果對映不包含此鍵的對映,則返回 null。

異常

從 Integer,Integer 對的 IdentityHashMap 獲取值的示例

以下示例演示瞭如何使用 Java IdentityHashMap get() 方法從 Map 中根據鍵獲取值。我們建立了一個 Integer,Integer 對的 Map 物件。然後添加了一些條目,列印對映。使用 get() 方法檢索並列印值。

package com.tutorialspoint;

import java.util.IdentityHashMap;

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

      // 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("Value: " + newmap.get(1));
   }    
}

輸出

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

Initial map elements: {2=2, 3=3, 1=1}
Value: 1

從 Integer,String 對的 IdentityHashMap 獲取值的示例

以下示例演示瞭如何使用 Java IdentityHashMap get() 方法從 Map 中根據鍵獲取值。我們建立了一個 Integer,String 對的 Map 物件。然後添加了一些條目,列印對映。使用 get() 方法檢索並列印值。

package com.tutorialspoint;

import java.util.IdentityHashMap;

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

      // 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("Value: " + newmap.get(1));
   }    
}

輸出

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

Initial map elements: {2=point, 3=is best, 1=tutorials}
Value: tutorials

從 Integer,Object 對的 IdentityHashMap 獲取值的示例

以下示例演示瞭如何使用 Java IdentityHashMap get() 方法從 Map 中根據鍵獲取值。我們建立了一個 Integer,Student 對的 Map 物件。然後添加了一些條目,列印對映。使用 get() 方法檢索並列印值。

package com.tutorialspoint;

import java.util.IdentityHashMap;

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

      // 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("Value: " + newmap.get(1));
   }    
}
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 ]}
Value: [ 1, Julie ]
java_util_identityhashmap.htm
廣告

© . All rights reserved.