WeakHashMap的java.util.WeakHashMap.put()方法用于将映射插入Map。这意味着我们可以将特定的键及其映射的值插入到特定的映射中。如果传递了现有键,则以前的值将被新值替换。如果传递了新的配对,则该配对将整体插入。
用法:
Weak_Hash_Map.put(key, value)
参数:该方法有两个参数,均为WeakHashMap的Object类型。
- key:这是指需要插入Map中进行映射的关键元素。
- value:这是指以上键将映射到的值。
返回值:如果传递了现有键,则返回先前的值。如果传递了新对,则返回NULL。
以下程序用于说明java.util.WeakHashMap.put()方法的用法:
示例1:传递现有 key 时。
// Java code to illustrate the put() method
import java.util.*;
public class Weak_Hash_Map_Demo {
public static void main(String[] args)
{
// Creating an empty WeakHashMap
Map<Integer, String> weak_hash = new
WeakHashMap<Integer, String>();
// Mapping string values to int keys
weak_hash.put(10, "Geeks");
weak_hash.put(15, "4");
weak_hash.put(20, "Geeks");
weak_hash.put(25, "Welcomes");
weak_hash.put(30, "You");
// Displaying the WeakHashMap
System.out.println("Initial Mappings are: " +
weak_hash);
// Inserting existing key along with new value
String returned_value =
(String)weak_hash.put(20, "All");
// Verifying the returned value
System.out.println("Returned value is: " +
returned_value);
// Displayin the new map
System.out.println("New map is: " + weak_hash);
}
}
输出:
Initial Mappings are: {30=You, 15=4, 10=Geeks, 25=Welcomes, 20=Geeks} Returned value is: Geeks New map is: {30=You, 15=4, 10=Geeks, 25=Welcomes, 20=All}
示例2:传递新 key 时。
// Java code to illustrate the put() method
import java.util.*;
public class Weak_Hash_Map_Demo {
public static void main(String[] args)
{
// Creating an empty WeakHashMap
Map<Integer, String> weak_hash = new
WeakHashMap<Integer, String>();
// Mapping string values to int keys
weak_hash.put(10, "Geeks");
weak_hash.put(15, "4");
weak_hash.put(20, "Geeks");
weak_hash.put(25, "Welcomes");
weak_hash.put(30, "You");
// Displaying the WeakHashMap
System.out.println("Initial Mappings are: " +
weak_hash);
// Inserting existing key along with new value
String returned_value =
(String)weak_hash.put(50, "All");
// Verifying the returned value
System.out.println("Returned value is: " +
returned_value);
// Displayin the new map
System.out.println("New map is: " + weak_hash);
}
}
输出:
Initial Mappings are: {30=You, 15=4, 10=Geeks, 25=Welcomes, 20=Geeks} Returned value is: null New map is: {30=You, 15=4, 10=Geeks, 25=Welcomes, 20=Geeks, 50=All}
注意:可以对具有不同数据类型的变化和组合的任何类型的映射执行相同的操作。
相关用法
- Java WeakHashMap get()用法及代码示例
- Java WeakHashMap clear()用法及代码示例
- Java WeakHashMap entrySet()用法及代码示例
- Java WeakHashMap containsValue()用法及代码示例
- Java WeakHashMap containsKey()用法及代码示例
- Java WeakHashMap putall()用法及代码示例
- Java WeakHashMap size()用法及代码示例
- Java WeakHashMap remove()用法及代码示例
- Java WeakHashMap keySet()用法及代码示例
- Java WeakHashMap values()用法及代码示例
- Java WeakHashMap isEmpty()用法及代码示例
- Java Java.util.Collections.rotate()用法及代码示例
- Java Java lang.Long.highestOneBit()用法及代码示例
注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 WeakHashMap put() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。