import java.util.HashMap;
import java.util.Map;
public class BasicHashMap {
public static void main(String[] args) {
// 新建map
Map<String, Integer> fstMap = new HashMap<>();
// 存值
fstMap.put("a", 1);
fstMap.put("b", 2);
fstMap.put("c", 3);
fstMap.put("d", 4);
System.out.println("=== fstMap 输出 ===");
System.out.println(fstMap);
Map<String, Integer> sndMap = new HashMap<>();
sndMap.put("ab", 1);
sndMap.put("cd", 2);
System.out.println("=== aMap.putAll(bMap) ===");
sndMap.putAll(fstMap);
System.out.println("合并后的sndMap");
System.out.println(sndMap);
System.out.println("合并后的fstMap剩余");
System.out.println(fstMap);
System.out.println("=== map.getOrDefault(aKey, dV), 有akey则返回相应的值,否则返回dV ===");
System.out.println(sndMap.getOrDefault("ab", 3));
System.out.println(sndMap.getOrDefault("m", 3));
System.out.println(sndMap);
System.out.println("=== map.put(aKey) 重复key===");
System.out.println("map put重复值,会先做get,返回对应值,再put;没有重复值,直接put,返回null");
System.out.println(sndMap.put("a", 5));
System.out.println(sndMap.put("z", 10086));
System.out.println(sndMap);
System.out.println("=== map.remove(aKey) VS map.remove(aKey, aValue) ===");
System.out.println("map remove(akey)操作:如果有akey,先get返回对应的值,再delete; 否则,返回null");
System.out.println(sndMap.remove("a"));
System.out.println(sndMap.remove("m"));
System.out.println("map remove(aKey, aValue)操作,返回true or false,以表明是否remove成功");
System.out.println(sndMap.remove("b", 2));
System.out.println(sndMap.remove("m", 8));
System.out.println(sndMap);
System.out.println("=== map.clear() ===");
sndMap.clear();
System.out.println(sndMap);
}
}
out:
=== fstMap 输出 ===
{a=1, b=2, c=3, d=4}
=== aMap.putAll(bMap) ===
合并后的sndMap
{ab=1, cd=2, a=1, b=2, c=3, d=4}
合并后的fstMap剩余
{a=1, b=2, c=3, d=4}
=== map.getOrDefault(aKey, dV), 有akey则返回相应的值,否则返回dV ===
1
3
{ab=1, cd=2, a=1, b=2, c=3, d=4}
=== map.put(aKey) 重复key===
map put重复值,会先做get,返回对应值,再put;没有重复值,直接put,返回null
1
null
{ab=1, cd=2, a=5, b=2, c=3, d=4, z=10086}
=== map.remove(aKey) VS map.remove(aKey, aValue) ===
map remove(akey)操作:如果有akey,先get返回对应的值,再delete; 否则,返回null
5
null
map remove(aKey, aValue)操作,返回true or false,以表明是否remove成功
true
false
{ab=1, cd=2, c=3, d=4, z=10086}
=== map.clear() ===
{}