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