Java HashMap put()方法

Java HashMap put()方法

HashMap的java.util.HashMap.put()方法是用来将一个映射插入到一个Map中。这意味着我们可以将一个特定的键和它所映射的值插入到一个特定的Map中。如果传递的是一个现有的键,那么之前的值就会被新的值所取代。如果传递了一个新的配对,那么这个配对就会被作为一个整体插入。

语法:

Hash_Map.put(key, value)
Java

参数: 该方法需要两个参数,都是HashMap的对象类型。

  • key: 这是指需要插入到Map中进行映射的关键元素。
  • value: 这指的是上述键将映射成的值。

返回值: 如果传递了一个现有的键,那么将返回之前的值。如果传递了一个新的配对,则返回NULL。
以下程序用于说明java.util.HashMap.put()方法的工作:

程序1: 当传递一个现有的键时。

// Java code to illustrate the put() method
import java.util.*;
  
public class Hash_Map_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty HashMap
        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  
        // Mapping string values to int keys
        hash_map.put(10, "Geeks");
        hash_map.put(15, "4");
        hash_map.put(20, "Geeks");
        hash_map.put(25, "Welcomes");
        hash_map.put(30, "You");
  
        // Displaying the HashMap
        System.out.println("Initial Mappings are: " + hash_map);
  
        // Inserting existing key along with new value
        String returned_value = (String)hash_map.put(20, "All");
  
        // Verifying the returned value
        System.out.println("Returned value is: " + returned_value);
  
        // Displaying the new map
        System.out.println("New map is: " + hash_map);
    }
}
Java

输出

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}
Java

程序2: 当传递一个新的密钥时。

// Java code to illustrate the put() method
import java.util.*;
  
public class Hash_Map_Demo {
    public static void main(String[] args)
    {
  
        // Creating an empty HashMap
        HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  
        // Mapping string values to int keys
        hash_map.put(10, "Geeks");
        hash_map.put(15, "4");
        hash_map.put(20, "Geeks");
        hash_map.put(25, "Welcomes");
        hash_map.put(30, "You");
  
        // Displaying the HashMap
        System.out.println("Initial Mappings are: " + hash_map);
  
        // Inserting existing key along with new value
        String returned_value = (String)hash_map.put(50, "All");
  
        // Verifying the returned value
        System.out.println("Returned value is: " + returned_value);
  
        // Displaying the new map
        System.out.println("New map is: " + hash_map);
    }
}
Java

输出

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}
Java

注意: 同样的操作可以通过不同数据类型的变化和组合对任何类型的Mapping进行操作。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册