概述
Map<K,V> 是一个双列集合
- K:键
- V:值
- 键唯一 ,值可以重复
- key和Value是一一对应的
常用实现类
HashMap<K,V>
特点:
- 底层是哈希表,查询速度特别快
(jdk1.8之前数组+单向链表)
(jdk1.8之后数组+单向链表/红黑树)链表长度超过8就转红黑树
- HashMap是一个无序的集合
LinkedHashMap
特点:
- 底层是哈希表+链表
- 有序的集合
HashMap 常用方法
public V put(K key, V value)
把指定的键值添加到集合
返回值是V key不重复 返回值v为null
public V remove(Object key)
删除指定的键
返回值是V key存在,v返回被删除的值 key不存在 返回的是null
public V get(Object key)
返回key对应的value值
boolean containsKey(Object key)
判断是否有该键
public Set<K> keySet()
获得所有的键 存储到Set集合中
public Set<Map.Entry<K,V>> entrySet()
获取到Map集合中所有的键值对对象的集合
public static void show01(){
Map<String,String> map = new HashMap<>();
map.put("谢霆锋","王菲");
map.put("黄晓明","Angelababy");
String v = map.put("李晨","范冰冰1");
System.out.println("v"+v); //null
String v2 = map.put("李晨","范冰冰2");
System.out.println("v2"+v2); //范冰冰1
System.out.println(map);//{李晨=范冰冰2, 谢霆锋=王菲, 黄晓明=Angelababy}
System.out.println(map.get("谢霆锋"));//王菲
System.out.println(map.containsKey("黄晓明"));//true
}
遍历map集合
两个方法:keySet() 、entrySet()
keySet():键找值方式 ->把Map集合取出来存储到Set集合,迭代器/增强for循环set,通过map的get(key)找到key对应的value
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("范冰冰",170);
map.put("林志玲",173);
map.put("王菲",172);
//把Map集合取出来存储到Set集合
Set<String> set = map.keySet();
//迭代器
Iterator<String> it = set.iterator();
while(it.hasNext()){
//通过map的get(key),找到key对应的value
String key = it.next();
Integer value = map.get(key);
System.out.println(key+"="+value);
}
System.out.println("---------");
//增强for
for (String key1 : set) {
Integer value = map.get(key1);
System.out.println(key1+"="+value);
}
}
entrySet():键值对对象
Map.Entry<K,V>:在Map接口在有个内部接口Entry,来记录键与值
步骤:
- 使用Map集合的entrySet().把Map集合多个Entry对象取出来,存到Set里
- 遍历Set集合,获取每一个Entry对象
- 使用Entry对象中的getkey()和getValue()获取键与值
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<>();
map.put("范冰冰",170);
map.put("林志玲",173);
map.put("王菲",172);
//使用entrySet(),用set存储
Set<Map.Entry<String,Integer>> set = map.entrySet();
//迭代器遍历
Iterator<Map.Entry<String,Integer>> it = set.iterator();
while(it.hasNext()){
Map.Entry<String,Integer> entry = it.next();
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key+"="+value);
}
System.out.println("------");
for (Map.Entry<String, Integer> entry : set) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + "=" + value);
}
注意:Map集合保证key是唯一的 所以要重写hashcode方法
Hashtable<K,V> implement Map<K,V>接口
底层是哈希表,线程安全,是单线程集合,速度慢,Key Value不能存储null
它的子类Properties依然活跃