Java IdentityHashMap put() 方法



描述

Java IdentityHashMap put(K key, V value) 方法用於將指定的值與此標識雜湊對映中的指定鍵關聯。如果對映先前包含此鍵的對映,則替換舊值。

宣告

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

public V put(K key, V value)

引數

  • key − 這是要與其關聯指定值的鍵。

  • value − 這是要與指定鍵關聯的值。

返回值

方法呼叫返回與鍵關聯的上一個值,如果鍵沒有對映,則返回 null。

異常

向 Integer,Integer 對的 IdentityHashMap 新增條目示例

以下示例演示了 Java IdentityHashMap put() 方法的使用,用於將一些值放入 Map 中。我們建立了一個 Integer,Integer 對的 Map 物件。然後使用 put() 方法添加了一些條目,然後列印了 Map。

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("Map elements: " + newmap);
   }    
}

輸出

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

Map elements: {2=2, 3=3, 1=1}

向 Integer,String 對的 IdentityHashMap 新增條目示例

以下示例演示了 Java IdentityHashMap put() 方法的使用,用於將一些值放入 Map 中。我們建立了一個 Integer,String 的 Map 物件。然後使用 put() 方法添加了一些條目,然後列印了 Map。

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("Map elements: " + newmap);
   }    
}

輸出

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

Map elements: {2=point, 3=is best, 1=tutorials}

向 Integer,Object 對的 IdentityHashMap 新增條目示例

以下示例演示了 Java IdentityHashMap put() 方法的使用,用於將一些值放入 Map 中。我們建立了一個 Integer,Student 對的 Map 物件。然後使用 put() 方法添加了一些條目,然後列印了 Map。

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("Map elements: " + newmap);
   }    
}
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 + " ]";
   }
}

輸出

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

Map elements: {1=[ 1, Julie ], 3=[ 3, Adam ], 2=[ 2, Robert ]}
java_util_identityhashmap.htm
廣告