java putifabsent_Java HashMap putIfAbsent(key, value)用法及代码示例

仅当此HashMap实例中不存在这样的映射时,才使用HashMap类的putIfAbsent(K key,V value)方法来映射具有指定值的指定键。

用法:

public V putIfAbsent(K key, V value)

参数:此方法接受两个参数:

key:这是必须映射提供的值的键。

value:如果不存在,则为必须与提供的键相关联的值。

返回值:此方法返回null(如果之前没有与提供的键的映射,或者已映射为null值)或与提供的键关联的先前值。

异常:此方法引发以下异常:

IllegalArgumentException:如果指定的键或值阻止其存储在Map中。

程序1:

// Java program to demonstrate

// putIfAbsent(Key, value) method.

import java.util.*;

public class GFG {

// Main method

public static void main(String[] args)

{

// create a HashMap and add some values

HashMap map

= new HashMap<>();

map.put("a", 10000);

map.put("b", 55000);

map.put("c", 44300);

map.put("e", 53200);

// print original map

System.out.println("HashMap:\n "

+ map.toString());

// put a new value which is not mapped

// before in map

map.putIfAbsent("d", 77633);

// print newly mapped map

System.out.println("New HashMap:\n "

+ map);

}

}

输出:

HashMap:

{a=10000, b=55000, c=44300, e=53200}

New HashMap:

{a=10000, b=55000, c=44300, d=77633, e=53200}

程序2:

// Java program to demonstrate

// putIfAbsent(Key, value) method.

import java.util.*;

public class GFG {

// Main method

public static void main(String[] args)

{

// create a HashMap and add some values

HashMap map

= new HashMap<>();

map.put("a", 10000);

map.put("b", 55000);

map.put("c", 44300);

map.put("e", null);

// print original map

System.out.println("HashMap:\n "

+ map.toString());

// put a new value which is not mapped

// before in map and store the returned

// value in r1

Integer r1 = map.putIfAbsent("d", 77633);

// put a new value for key 'e' which is mapped

// with a null value, and store the returned

// value in r2

Integer r2 = map.putIfAbsent("e", 77633);

// print the value of r1

System.out.println("Value of r1:\n " + r1);

// print the value of r2

System.out.println("Value of r2:\n " + r2);

// print newly mapped map

System.out.println("New HashMap:\n "

+ map);

}

}

输出:

HashMap:

{a=10000, b=55000, c=44300, e=null}

Value of r1:

null

Value of r2:

null

New HashMap:

{a=10000, b=55000, c=44300, d=77633, e=77633}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值