put和putIfAbsent的区别

本文探讨了Java Map中put方法和putIfAbsent方法的区别。put方法会在key不存在时添加键值对,若key已存在则替换原有值并返回旧值。而putIfAbsent方法仅在key不存在时添加键值对,返回值为null或原有的值。
摘要由CSDN通过智能技术生成

1.使用 put 方法添加键值对,如果 map 集合中没有该 key 对应的值,则直接添加,并返回 value;如果已经存在对应的值,则会覆盖旧值,value 为新的值,返回值为 value。

2.使用 putIfAbsent 方法添加键值对,如果 map 集合中没有该 key 对应的值,则直接添加,并返回 null,如果已经存在对应的值,则依旧为原来的值,返回值为 value(旧的值)。

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt&g
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值