2019-01-03
2019-01-04 本文已影响1人
DreamPath
Map集合
Map集合
1.1Map集合概念
- Map集合是一种存放关系对象的对象的双列集合。
1.2Map集合的常用子类
HashMap<K,V>
- 1.数据存储方式:哈希表结构。
- 2.存储情况:无序性
- 3.保证键的唯一性方式:需要重写键的hashCode()方法、equals()方法。
LinkedHashMap<K,V>,是HashMap的一个子类。
- 1.数据存储方式:哈希表结构+链表结构
存储数据采用的哈希表结构+链表结构。
(1.链表结构:保证元素的存取顺序一致。
(2.哈希表结构:保证的键的唯一、不重复。 - 3.同样需要重写键的 hashCode()方法、equals()方法。
注意:K, V泛型类型可以一致,也可以不一致。
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* @author lx
* @date 2019/1/3 - 17:25
* public V put(K key, V value) : 把指定的键与指定的值添加到Map集合中。
* public V remove(Object key) : 把指定的键 所对应的键值对元素 在Map集合中删除,返回被删除元素的值。
* public V get(Object key) 根据指定的键,在Map集合中获取对应的值。
* boolean containsKey(Object key) 判断集合中是否包含指定的键。
* public Set<K> keySet() : 获取Map集合中所有的键,存储到Set集合中。
* public Set<Map.Entry<K,V>> entrySet() : 获取到Map集合中所有的键值对对象的集合(Set集合)
*/
public class HashMapDemo {
public static void main(String[] args) {
HashMap<String, String> hashMap = new HashMap<>();
//添加元素
hashMap.put("冯小刚", "范冰冰");
hashMap.put("李晨", "范冰冰");
//如果键相同,值不同时,直接会覆盖前面的Value值。
hashMap.put("冯小刚", "徐帆");
hashMap.put("冯绍峰", "赵丽颖");
hashMap.put("霍建华", "林心如");
hashMap.put("杨幂", "刘恺威");
System.out.println(hashMap);
//{冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰, 杨幂=刘恺威}
//通过Key删除元素
hashMap.remove("杨幂");
System.out.println(hashMap);
//{冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰}
//获取指定键key的value值
String s = hashMap.get("霍建华");
System.out.println(s);//林心如
//判断集合中是否包含指定键
System.out.println(hashMap.containsKey("杨幂"));//在这之前已经被删除了,返回false
//判断集合中是否含有指定value值(一般很少用)
System.out.println(hashMap.containsValue("范冰冰"));//true
//获取集合中的所有键,并存储到集合中
Set<String> set=hashMap.keySet();
System.out.println(set);//[冯绍峰, 霍建华, 冯小刚, 李晨]
//获取 键值对 对象的集合
Set<Map.Entry<String,String>> set1=hashMap.entrySet();
System.out.println(set1);//[冯绍峰=赵丽颖, 霍建华=林心如, 冯小刚=徐帆, 李晨=范冰冰]
//遍历获取到的键值对的集合
for (Map.Entry<String,String> ss:set1) {
System.out.println(ss);
/*
冯绍峰=赵丽颖
霍建华=林心如
冯小刚=徐帆
李晨=范冰冰
*/
}
}
}
Entry键值对对象
- Key(键)+Value(值)=Map集合中的Entry项。
- Entry将键值对封装成了键值对 对象。方便了我们从每一个Entry对象中获取对应的键与对应的值。