Java AbstractMap put()方法及示例
AbstractMap的AbstractMap.put()方法是用来将一个映射插入一个地图中的。这意味着我们可以在一个特定的地图中插入一个特定的键和它所映射的值。如果传递的是一个现有的键,那么之前的值就会被新的值所取代。如果传递了一个新的配对,那么这个配对就会被作为一个整体插入。
语法
AbstractMap.put(key, value)
参数: 该方法需要两个参数,都是AbstractMap的对象类型。
- key。 指的是需要插入到Map中进行映射的关键元素。
- value。 这指的是上述键将映射成的值。
返回值: 如果一个现有的键被传递,那么以前的值会被返回。如果传递的是一个新的配对,则返回NULL。
下面的程序用来说明AbstractMap.put()方法的工作原理。
程序1: 当传递一个现有的键时。
// Java code to illustrate the put() method
import java.util.*;
public class Abstract_Map_Demo {
public static void main(String[] args)
{
// Creating an empty AbstractMap
AbstractMap<Integer, String>
abs_map = new HashMap<Integer, String>();
// Mapping string values to int keys
abs_map.put(10, "Geeks");
abs_map.put(15, "4");
abs_map.put(20, "Geeks");
abs_map.put(25, "Welcomes");
abs_map.put(30, "You");
// Displaying the AbstractMap
System.out.println("Initial Mappings are: "
+ abs_map);
// Inserting existing key along with new value
String
returned_value
= (String)abs_map.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: "
+ abs_map);
}
}
输出。
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {20=All, 25=Welcomes, 10=Geeks, 30=You, 15=4}
程序2: 当传递一个新的密钥时。
// Java code to illustrate the put() method
import java.util.*;
public class Abstract_Map_Demo {
public static void main(String[] args)
{
// Creating an empty AbstractMap
AbstractMap<Integer, String>
abs_map = new HashMap<Integer, String>();
// Mapping string values to int keys
abs_map.put(10, "Geeks");
abs_map.put(15, "4");
abs_map.put(20, "Geeks");
abs_map.put(25, "Welcomes");
abs_map.put(30, "You");
// Displaying the AbstractMap
System.out.println("Initial Mappings are: "
+ abs_map);
// Inserting existing key along with new value
String
returned_value
= (String)abs_map.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: " + abs_map);
}
}
输出。
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {50=All, 20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
注意: 同样的操作可以通过不同数据类型的变化和组合对任何类型的Mapping进行操作。
极客教程