2. Map接口
2.1 概述
Map接口是将键映射到值的对象。一个映射不呢个包含重复的键,每个键最多只能映射到一个值,值可以重复。
2.2 Map接口的常用方法
public static void main(String[] args) {
Map<String,String> map=new HashMap<>();
//1.添加元素
map.put("cn", "中国");
map.put("usa", "美国");
map.put("uk", "英国");
map.put("kr", "韩国");
map.put("cn", "中华人民共和国");
System.out.println("打印"+map.toString());
//2.删除
map.remove("kr");
System.out.println("删除之后:"+map.toString());
//3.遍历
//3.1使用keySet遍历
System.out.println("-----------------------");
Set<String> keyset=map.keySet();
for (String s : keyset) {
System.out.println(s+"-------"+map.get(s));
}
//3.2使用entrySet遍历
System.out.println("-------entrySet--------------");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Map.Entry<String, String> entry : entries) {
System.out.println(entry.getKey()+"------"+entry.getValue());
}
//4.判断
//4.1判断key是否存在
System.out.println(map.containsKey("cn"));
//4.2判断value是否存在
System.out.println(map.containsValue("美国"));
}
2.3 Map常用实现类
2.3.1 HashMap
基于哈希表的Map接口的实现。此实现提供所有可选的映射操作,并允许使用null键和null值。子类不保证映射的顺序。
存储特点:相对无序存储,元素以键值对形式存在,键不可以重复,值可以重复
元素整体排重(键值对),可以快速通过键查找对应的值,通过哈希表实现的集合
HashMap遍历:
public static void main(String[] args) {
HashMap<String,String> hashMap=new HashMap<>();
//1.添加元素
hashMap.put("huawei", "华为");
hashMap.put("mimi", "小米");
hashMap.put("apple", "苹果");
hashMap.put("lenovo", "联想");
hashMap.put("apple", "小苹果");
System.out.println(hashMap.toString());
//2.删除
hashMap.remove("apple");
System.out.println(hashMap.toString());
//3遍历
System.out.println("---------------------");
//3.1keySet的增强for
for (String s : hashMap.keySet()) {
System.out.println(s+"="+hashMap.get(s));
}
//3.2entrySet
System.out.println("---------------------");
for (Map.Entry<String, String> st : hashMap.entrySet()) {
System.out.println(st);
}
}
2.3.2 LinkedHashMap
具有可预知迭代顺序的Set接口的哈希表和链接列表实现
存储特点:有序存储,元素排重,通过链表实现的集合
2.3.3 Hashtable
此类实现一个哈希表,该哈希表将键映射到相应的值。任何非null对象都可以用作键或值
存储特点:相对无序存储,元素排重,通过哈希表实现的集合
2.3.4 HashMap与Hashtable的区别
(1)Hashtable线程安全的,HashMap线程不安全的
(2)Hashtable中不允许存在null键和null值,但是HashMap中允许
2.3.5 TreeMap
存储结构:自平衡红黑二叉树
特点:(1)存储键值对、键不能重复,值可以重复,一个键对应一个值;
(2)无序,数据会进行排序。