上源码
Method Returns
The getOrDefault() method returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.
直译一下就是当HashMap集合中有这个key时,如果存在则return it,如果没有就使用默认值defaultValue
举例
public static void main(String[] args)
{
HashMap<String, Integer> map
= new HashMap<>();
map.put("a", 100);
map.put("b", 200);
map.put("c", 300);
map.put("d", 400);
System.out.println("HashMap: "
+ map.toString());
int k = map.getOrDefault("b", 500);
System.out.println("Returned Value: " + k);
}
//输出
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 200
示例2
```java
public static void main(String[] args)
{
HashMap<String, Integer> map
= new HashMap<>();
map.put("a", 100);
map.put("b", 200);
map.put("c", 300);
map.put("d", 400);
System.out.println("HashMap: "
+ map.toString());
int k = map.getOrDefault("y", 500);
System.out.println("Returned Value: " + k);
//输出
HashMap: {a=100, b=200, c=300, d=400}
Returned Value: 500