HashMap中的putIfAbsent使用示例
原文:https://blog.csdn.net/k3108001263/article/details/83720445
- 如果不存在key,则添加到HashMap中,跟put方法相似
- 如果存在key,则不会覆盖,HashMap不受影响,而put方法会覆盖更新
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}
看完打开支付宝扫一扫领个红包吧!