Map接口的实现类HashMap的常用方法
1、Map集合的特点
- Map集合是双列集合,由key和value组成。称之为键值对
- 键的特点:无序,无下标,不重复。
- 值的特点:无序,无下标,可重复
2、Map集合体系结构
3、Map集合的常用方法
- 常用方法:
put(K key, V value)
get(Object key)
Set keySet()
Collection values()
Set<Map.Entry<K,V>> entrySet()
boolean containsKey(Object key)
boolean containsValue(Object value)
V remove(Object key)
int size()
public class HashMapDemo{
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("CN","中国");
map.put("HK","香港");
map.put("CNHK","香港");
map.put("UK","英国");
map.put("CN","中华人民共和国");
System.out.println(map);
System.out.println(map.get("CN"));
System.out.println(map.get("CNHK"));
Set<String> keySet = map.keySet();
for (String s : keySet) {
System.out.print(s+"\t");
}
Collection<String> values = map.values();
for (String value : values) {
System.out.print(value+"\t");
}
System.out.println();
Set<Map.Entry<String, String>> entrySet = map.entrySet();
for (Map.Entry<String, String> entry : entrySet) {
System.out.print(entry.getKey()+":"+entry.getValue()+"\t");
}
System.out.println(map.containsKey("JP"));
System.out.println(map.containsValue("香港"));
System.out.println(map.isEmpty());
String s = map.remove("USA");
System.out.println(s);
System.out.println(map);
System.out.println(map.size());
System.out.println("=====================================================");
String s1 = map.put("TD", "中国台湾");
String s2 = map.put("TD", "中国台湾省");
System.out.println(s1);
System.out.println(s2);
}
}
4、HashMap的底层实现原理