Java中的Java.util.EnumMap.put(key,value)方法用於關聯指定的鍵-值對。在這種情況下,如果重複這些值,則替換較舊的值。
用法:
Enum_Map.put(key, value)
使用的參數:該方法有兩個參數。
- key–它是與值關聯的指定鍵。
- value–它是與指定鍵關聯的值。
返回值:該函數返回與指定鍵關聯的舊值。
以下程序說明了put(key,value)方法的用法原理:
示例1:
// Java program to demonstrate keySet()
import java.util.*;
// An enum of geeksforgeeks
public enum gfg {
Global_today,
India_today,
China
}
;
class Enum_demo {
public static void main(String[] args)
{
EnumMap<gfg, Integer> mp = new
EnumMap<gfg, Integer>(gfg.class);
// Values are associated
mp.put(gfg.Global_today, 799);
mp.put(gfg.India_today, 69);
// Display the initial map
System.out.println("The map is: " + mp);
// Stores the old value associated with the key
int prev_value = mp.put(gfg.India_today, 72);
// Prints the old value
System.out.println("Previous value: " + prev_value);
// Display the final map
System.out.println("The final map is: " + mp);
}
}
輸出:
The map is: {Global_today=799, India_today=69} Previous value: 69 The final map is: {Global_today=799, India_today=72}
示例2:
// Java program to demonstrate the working of keySet()
import java.util.*;
// an enum of geeksforgeeks
// ranking globally and in india
public enum gfg {
Global_today,
India_today,
China_today
}
;
class Enum_demo {
public static void main(String[] args)
{
EnumMap<gfg, Integer> mp = new EnumMap<gfg, Integer>(gfg.class);
// Values are associated
mp.put(gfg.Global_today, 799);
mp.put(gfg.India_today, 69);
// Display the initial map
System.out.println("The map is: " + mp);
// Stores the old value associated with the key
int prev_value = mp.put(gfg.Global_today, 800);
// Prints the old value
System.out.println("Previous value: " + prev_value);
// Display the final map
System.out.println("The final map is: " + mp);
}
}
輸出:
The map is: {Global_today=799, India_today=69} Previous value: 799 The final map is: {Global_today=800, India_today=69}
相關用法
- Java EnumMap get()用法及代碼示例
- Java EnumMap containsKey()用法及代碼示例
- Java EnumMap clone()用法及代碼示例
- Java EnumMap entrySet()用法及代碼示例
- Java EnumMap remove()用法及代碼示例
- Java EnumMap containsValue(value)用法及代碼示例
- Java EnumMap size()用法及代碼示例
- Java EnumMap putAll(map)用法及代碼示例
- Java EnumMap keySet()用法及代碼示例
- Java EnumMap values()用法及代碼示例
- Java EnumMap equals()用法及代碼示例
- Java EnumMap clear()用法及代碼示例
- Java EnumMap用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
注:本文由純淨天空篩選整理自akash1295大神的英文原創作品 EnumMap put() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。