爪哇。util。哈希表。Hashtable的put()方法用于将映射插入表中。这意味着我们可以将一个特定的键及其映射到的值插入到一个特定的表中。如果传递了一个现有的密钥,那么以前的值将被新值替换。如果通过了一个新的对,则该对将作为一个整体插入。
null
语法:
Hash_Table.put(key, value)
参数: 该方法有两个参数,都是哈希表的对象类型。
- 关键: 这是指需要插入表中进行映射的关键元素。
- 价值: 这是指上面的键将映射到的值。
返回值: 如果传递了现有密钥,则返回上一个值。如果传递了一个新的对,则返回NULL。
下面的程序用来说明java的工作原理。util。哈希表。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); } } |
输出:
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: 传递新钥匙时。
// 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); } } |
输出:
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}
注: 可以对任何类型的变化和不同数据类型的组合执行相同的操作。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END