Java.util.Hashtable 类

java.util.Hashtable.replace() 方法仅用于替换指定键的条目当前映射到某个值。

语法

public V replace(K key, V value)

这里,K和V分别是容器维护的键和值的类型。

参数

h3>
key 指定与指定值关联的键。
value 指定与指定键关联的值。

返回值

返回与指定键关联的先前值,如果该键没有映射,则返回 null。 (如果实现支持 null 值,则 null 返回还可以指示映射先前将 null 与键关联。)

异常

无。

示例:

在下面的示例中,java.util.Hashtable.replace()方法用于替换给定哈希表中指定键的条目。

import java.util.*;

public class MyClass {
  public static void main(String[] args) {
    //创建哈希表
    Hashtable<Integer, String> Htable = new Hashtable<Integer, String>();

    //填充哈希表
    Htable.put(101, "John");
    Htable.put(102, "Marry");
    Htable.put(103, "Kim");

    //打印哈希表
    System.out.println("Before replace, Htable contains: " + Htable);    

    //替换与101键关联的值
    Htable.replace(101, "Sam"); 

    //打印哈希表
    System.out.println("After replace, Htable contains: " + Htable);  
  }
}

上述代码的输出将是:

Before replace, Htable contains: {103=Kim, 102=Marry, 101=John}
After replace, Htable contains: {103=Kim, 102=Marry, 101=Sam}