赞
踩
1、若映射中没有存储与给定键对应的信息,get方法会返回null;
如果希望返回你设定的默认值,使用getOrDefault方法。
//situation 1
var id = "00000000";
Employee e = staff.get(id);
//如果id不存在,不会报错,e == null
//situation 2
int score = scores.getOrDefault(id, 0);
//如果id不存在,score == 0
2、put方法有返回值,它会返回与这个键相关联的上一个值。
var sores = new HashMap<String, Integer>();
scores.put("Bob", 99);
int old = scores.put("Bob", 100);
//old == 99
3、迭代处理映射中的键与值
scores.forEach((k, v) ->
{
...
}
);
for(var entry : scores.entrySet())
{
System.out.println("key = " + entry.getKey());
System.out.println("value = " + entry.getValue());
}
4、remove(key)方法会删除一个键值对。
5、HashMap具有三个构造器,允许设置初始容量与装填因子(默认为0.75),一旦装填因子超过设置值,会再散列至一个更大的散列表中。
6、试想你需要通过映射统计一个单词在文件中出现的频度。
这样写是错误的:
counts.put(word, counts.get(word) + 1);
因为当第一次出现一个单词时,get函数返回null,因此会爆发NullPointerException异常。
以下有三种改写方式:
//Method 1
counts.put(word,counts.getOrDefault(word, 0) + 1);
//Method 2
counts.putIfAbsent(word, 0);
count.put(word, counts.get(word) + 1);
//Method 3
counts.merge(word, 1, Integer::sum);
merge方法的作用原理如下:
若key(word)相关联的值不是null,则将函数(Integer::sum)应用到原先相关联的值与函数中的数值(1),若结果非null,将key与结果相关联;若结果为null,将键删除。
若key原先没有关联值,将key与函数中的数值相关联。
这样就可以快速更新映射条目了。
7、映射视图
// 键集: Set<String> keys = staff.keySet(); for(String key : keys) { ... } //值集合: for(Empolyee employee : staff.values()) { ... } //键值对集: for(Map.Entry<String, Employee> entry : staff.entrySet()) //或写成 var entry : staff.entrySet() { String k = entry.getKey(); Employee v = entry.getValue(); ... }
注意 :
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。