
上QQ阅读APP看书,第一时间看更新
HashMap usage example
Here's the Java code that demonstrates some basic HashMap usage:
HashMap map = new HashMap();
map.put("key1", "value1");
map.put("key1", "value2");
map.putIfAbsent("key1", "value3");
System.out.println(map.get("key1"));
System.out.println(map.containsKey("value2"));
System.out.println(map.size());
This would print:
value2
false
1
The first printed line is value2 because the second map.put call overwrote the first value1 value with value2 and the map.putIfAbsent method call did nothing. It printed false as its second line because the map.containsKey method only looks for keys. The final printed line is 1 because only one key/value pair was stored.