Java中的WeakHashMap put()方法
WeakHashMap的java.util.WeakHashMap.put()方法用于将映射插入到映射中。这意味着我们可以将特定的键和其映射的值插入到特定的映射中。如果传递了现有的键,则先前的值将被新值替换。如果传递了新的对,则整个对将被插入。
语法:
Weak_Hash_Map.put(key, value)
参数: 该方法接受两个参数,都是WeakHashMap的Object类型。
- key:这是需要插入映射的键元素。
- value:这是上述键将映射到的值。
返回值: 如果传递了现有的键,则返回先前的值。如果传递了新的对,则返回NULL。
下面的程序用于说明java.util.WeakHashMap.put()方法的工作方式:
程序1: 当传递现有的键时。
// 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 weak_hash = new
WeakHashMap();
// 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: 当传递新的键时。
// 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 weak_hash = new
WeakHashMap();
// 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.util.WeakHashMap.put()方法的用法和语法,以及包含两个程序演示了方法的实现和输出结果。
注意: 可以使用不同的数据类型进行变化和组合,执行相同类型的映射操作。