Java HashMap replace()方法

java.util.HashMap.replace(K key, V value) 方法仅在先前将键映射为某个值时才用于替换指定键的值。

1 语法

public V replace(K key, V value)

2 参数

key:这是必须替换其值的元素的键。

value:这是必须与提供的键映射的新值。

3 返回值

该方法返回与指定键关联的先前值。如果没有映射的键,则返回null,如果实现支持null值。

4 示例 

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * java.util.HashMap.replace(K key, V value)方法的例子
 */
import java.util.*;

public class Demo {
    public static void main(String args[]) {

        // Create a HashMap and add some values
        HashMap<String, Integer> map
                = new HashMap<>();
        map.put("a", 100);
        map.put("b", 300);
        map.put("c", 300);
        map.put("d", 400);

        // print map details
        System.out.println("HashMap: "
                + map.toString());

        // provide value for the key which has
        // to replace it's current value,
        // using replace(K key, V value) method
        map.replace("b", 200);

        // print new mapping
        System.out.println("New HashMap: "
                + map.toString());
    }
}

输出结果为:

HashMap: {a=100, b=300, c=300, d=400}
New HashMap: {a=100, b=200, c=300, d=400}

热门文章

优秀文章