HashMap
众所周知,HashMap是一个用于存储Key-Value键值对的集合,每一个键值对也叫做Entry。这些个键值对(Entry)分散存储在一个数组当中,这个数组就是HashMap的主干。
HashMap数组每一个元素的初始值都是Null。
HashMap<String, String> hash = new HashMap<>();
hash.get("name");
输出
null
如上,HashMap获取值的方法是get(key),对应的设置key的方式是put(key, value)
hash.put("color", "red");
hash.put("name", "xiaohong");
hash.put("gender", "male");
hash.put("age", "18");
hash.put("birthday", "1990-10-01");
System.out.println(hash.get("birthday"));
输出
1990-11-01
如果再次put已存在的key,会用新值替换旧值
hash.put("birthday", "1990-11-11");
System.out.println(hash.get("birthday"));
输出
1990-11-11
设置key的另一个方法是putIfAbsent(key, value),和put不一样的是,如果key已存在,就不会替换值
hash.putIfAbsent("birthday", "1990-11-11");
System.out.println(hash.get("birthday"));
输出依然是1990-10-01
1990-10-01
putIfAbsent
与put不同,当key存在时候,不会替换原有值
hash.put("birthday", "1990-10-01");
hash.putIfAbsent("birthday", "1990-11-01");
System.out.println(hash.get("birthday"));
输出
1990-10-01
putAll
将已有的hashMap赋值到另一个hashMap
public static void main(String[] args) {
HashMap<String, String> hash = new HashMap<>();
hash.put("color", "red");
hash.put("name", "xiaohong");
hash.put("gender", "male");
hash.put("age", "18");
hash.put("birthday", "1990-10-01");
HashMap<String, String> mainHash = new HashMap<>();
mainHash.put("type", "main");
mainHash.putAll(hash);
System.out.println(mainHash);
}
输出
{birthday=1990-10-01, color=red, gender=male, name=xiaohong, type=main, age=18}
getOrDefault
看名字就知道意思,当key不存在时候,就会返回第二个参数的值作为默认值
System.out.println(mainHash.getOrDefault("id", "aaa"));
mainHash.put("id", "bbb");
System.out.println(mainHash.getOrDefault("id", "aaa"));
输出
aaa
bbb
replace方法
可以选择2到3个参数
当为2个参数时,replace.replace(key, newValue)
hash.put("age", "18");
System.out.println(mainHash);
mainHash.replace("age", "20");
System.out.println(mainHash);
输出
18
20
当为3个参数时,replace.replace(key, oldValue, newValue)
hash.put("age", "18");
System.out.println(mainHash);
mainHash.replace("age", "19", "20");
System.out.println(mainHash);
mainHash.replace("age", "18", "20");
System.out.println(mainHash);
输出
18
18
20
可以看到,三个参数时候,如果第二个参数(oldValue)与当前的value不同,就替换失败