java hashtable put_Java Hashtable put()用法及代码示例

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}

注意:可以使用任何类型的变体以及不同数据类型的组合来执行相同的操作。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值