HashMap中的putIfAbsent使用示例

  • 如果不存在key,则添加到HashMap中,跟put方法相似
  • 如果存在key,则不会覆盖,HashMap不受影响,而put方法会覆盖更新
package com.eshore.common.util;

import java.util.HashMap;
import java.util.Map;

public class Test {
	public static void main(String[] args) throws Exception {
		Map<String, String> map = new HashMap<>();
		map.put("message", "hello");
		map.putIfAbsent("message", "world");
		System.out.println(map);
	}
}

打印结果是

{message=hello}

猜你喜欢

转载自blog.csdn.net/k3108001263/article/details/83720445