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 output===" ); 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( "The merged sndMap" ); System.out.println(sndMap); System.out.println( "The merged fstMap remains" ); System.out.println(fstMap); System.out.println( "=== map.getOrDefault(aKey, dV), if there is akey, return the corresponding value, otherwise return 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 duplicate value, will do get first, return the corresponding value, and then put; no duplicate value, put directly, return 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) operation: if there is akey, first get and return the corresponding value, and then delete; otherwise, return null" ); System.out.println(sndMap.remove("a")); System.out.println(sndMap.remove("m")); System.out.println( "map remove(aKey, aValue) operation, return true or false to indicate whether the remove is successful" ); 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 output === {a =1, b=2, c=3, d=4 } === aMap.putAll(bMap) === Merged sndMap {ab = 1, cd = 2, a = 1, b = 2, c = 3, d = 4 } Merged fstMap remaining {a =1, b=2, c=3, d=4 } === map.getOrDefault(aKey, dV), if there is akey, return the corresponding value, otherwise return dV === 1 3 {ab =1, cd=2, a=1, b=2, c=3, d=4 } === map.put(aKey) repeat key=== map put duplicate value, will do get first, return the corresponding value, and then put; no duplicate value, put directly, return 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) operation: if there is an akey, first get and return the corresponding value, and then delete; otherwise, return null 5 null map remove(aKey, aValue) operation, return true or false to indicate whether the remove is successful true false {ab =1, cd=2, c=3, d=4, z=10086 } === map.clear () === {}