import java.util.HashMap;import java.util.Map;public class BasicHashMap { public static void main(String[] args) { // 新建map MapfstMap = 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 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 ===13{ab=1, cd=2, a=1, b=2, c=3, d=4}=== map.put(aKey) 重复key===map put重复值,会先做get,返回对应值,再put;没有重复值,直接put,返回null1null{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; 否则,返回null5nullmap remove(aKey, aValue)操作,返回true or false,以表明是否remove成功truefalse{ab=1, cd=2, c=3, d=4, z=10086}=== map.clear() ==={}