Map<K,V> 接口中键和值一一映射. 可以通过键来获取值。
给定一个键和一个值,你可以将该值存储在一个Map对象,之后,你可以通过键来访问对应的值。当访问的值不存在的时候,方法就会抛出一个NoSuchElementException异常。当对象的类型和Map里元素类型不兼容的时候,就会抛出一个 ClassCastException异常。当在不允许使用Null对象的Map中使用Null对象,会抛出一个 NullPointerException 异常。当尝试修改一个只读的Map时,会抛出一个UnsupportedOperationException异常。
// 如果是基本数据类型,声明的map的时候使用包装类
Map<Integer, String> map = new HashMap<>();//HashMap用的比较多
Map<Integer, String> map2 = new Hashtable<>();//Hashtable用得比较少
// 添加数据 put(key,value)
map.put(0, "str0");
map.put(1, "str1");
map.put(2, null);
map.put(null, null);
System.out.println(map);
// 当key已经存在时,修改key值所对应的value值
map.put(null, "asdg");
map.put(2, "666");
System.out.println(map);
输出结果如下:
// 根据Key值移除映射关系 remove(key)
map.remove(null);
map.remove(2);
System.out.println(map);
// 判断key值是否存在 containsKey(key)
System.out.println("是否存在key:0 ---> " + map.containsKey(0));
// 判断value值是否存在 containsValue(value)
System.out.println("是否存在Value:null---> " +
map.containsValue(null));
// 清空map
map.clear();
System.out.println("清空clear():" + map);
// 判断是否为空
System.out.println("map是否为空:" + map.isEmpty());
输出结果如下:
//keySet():返回map中所有key值的集合(set集合)
Set<Integer> keysSet = map.keySet();
//输出查看返回的key值集合
System.out.println("key值集合:" + keysSet);
//foreach循环
for (Integer integer : keysSet) {
//get(key) 方法通过key值来获取value值
System.out.println("key值:" + integer +
"-->value值:" + map.get(integer));
}
//size():返回此映射中的键值映射关系数
System.out.println("size(): " + map.size());
输出结果如下: