1—Map集合
Map集合的概述
interface Map<Key,Value>//Key:键的类型Value:值的类型
由上述可知,Map是一个接口,内部是由键值对组成,每一个键对应一个值
Map集合的特点
Map集合是双列集合,键是唯一的,不可重复。值可以重复
Map基本使用
Map集合与Set集合都采用多态的形式创建集合对象
代码示例:
public class MapDemo1{
public static void main(String[] args) {
//多态的方式创建集合对象
// Map<Key,Value> Key和Value的类型
//如果是基本类型,那么都是其包装类类型,
//也可自定义类型 如<Integer,Student> 类型 键为Integer类型 值为自定义的学生类型
Map<String,String> map = new HashMap<String,String>();
//调用Map集合的put方法添加元素
map.put("itheima001","林青霞");
map.put("itheima002","张曼玉");
map.put("itheima003","王祖贤");
map.put("itheima003","柳岩");
//输出集合对象
System.out.println(map);
}
}
Map集合的方法
代码示例:
public class MapDemo02 {
public static void main(String[] args) {
//创建集合对象
Map<String,String> map = new HashMap<String,String>();
//V put(K key,V value):添加元素
map.put("张无忌","赵敏");
map.put("郭靖","黄蓉");
map.put("杨过","小龙女");
//V remove(Object key):根据键删除键值对元素
System.out.println(map.remove("郭靖"));
System.out.println(map.remove("郭襄"));
//void clear():移除所有的键值对元素
map.clear();
//boolean containsKey(Object key):判断集合是否包含指定的键
System.out.println(map.containsKey("郭靖"));
System.out.println(map.containsKey("郭襄"));
//boolean isEmpty():判断集合是否为空
System.out.println(map.isEmpty());
//int size():集合的长度,也就是集合中键值对的个数
System.out.println(map.size());
//输出集合对象
System.out.println(map);
}
}
Map集合的获取功能
代码示例:
public class MapDemo03 {
public static void main(String[] args) {
//创建集合对象
Map<String, String>