Java Hashtable put()方法

Java Hashtable put()方法

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

语法

Hash_Table.put(key, value)
Java

参数: 该方法需要两个参数,都是Hashtable的Object类型。

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

返回值: 如果一个现有的键被传递,那么以前的值会被返回。如果传递的是一个新的配对,则返回NULL。

下面的程序用来说明java.util.Hashtable.put()方法的工作:

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

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

输出:

Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: Geeks
New table is: {10=Geeks, 20=All, 30=You, 15=4, 25=Welcomes}
Java

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

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

输出:

Initial table is: {10=Geeks, 20=Geeks, 30=You, 15=4, 25=Welcomes}
Returned value is: null
New table is: {10=Geeks, 20=Geeks, 30=You, 50=All, 15=4, 25=Welcomes}
Java

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册