Hashtable的java.util.Hashtable.put()方法用于将映射插入表中。这意味着我们可以将特定的键及其映射的值插入到特定的表中。如果传递了现有键,则以前的值将被新值替换。如果传递了新的配对,则该配对将整体插入。
用法:
Hash_Table.put(key, value)
参数:该方法有两个参数,都属于Hashtable的Object类型。
key:这是指需要插入到表中进行映射的关键元素。
value:这是指以上键将映射到的值。
返回值:如果传递了现有键,则返回先前的值。如果传递了新对,则返回NULL。
以下程序用于说明java.util.Hashtable.put()方法的用法:
示例1:传递现有 key 时。
// 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 hash_table =
new Hashtable();
// 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);
}
}
输出:
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}
示例2:传递新 key 时。
// 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 hash_table =
new Hashtable();
// 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);
}
}
输出:
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}
注意:可以使用任何类型的变体以及不同数据类型的组合来执行相同的操作。