Map接口中的常用方法

public V put (K key,V value):把指定的键与指定的值添加到Map集合中

​ 返回值:v
​ 存储键值对的时候,key不重复,返回值是null
​ 存储键值对的时候,key重复,会使用新的value替代map中重复的value,返回被替换的value值

public static void show01() {
    //创建Map集合对象,多态
    Map<String,String> map = new HashMap<>();
    String v1 = map.put("李晨","范冰冰1");
    System.out.println("v1"+v1);//v1:null
    String v2 = map.put("李晨","范冰冰2");
    System.out.println("v2"+v2);//v2:范冰冰1
}

 public V remove (Object key):把指定的键,所对应的键值对元素,在Mao集合中删除,返回被删除元素的值

​ 返回值:V
​ key存在,v返回被删除的值
​ key不存在,v返回null

public static void show02() {    //创建Map集合对象    Map<String,Integer> map = new HashMap<>();  
  map.put("赵丽颖",168);   
 map.put("杨逸",165);   
 System.out.println(map);//赵丽颖=168,杨逸=165   
 Integer v1 = map.remove("赵丽颖");    System.out.println(v1);//v1:168  
 Integer v2 = map.remove("杨怡");    System.out.println(v2);//v2:null
}

 public V get(Object key) 根据指定的键,在Map集合中获取对应的值

​ 返回值:
​ key存在,返回对应的value值
​ key不存在,返回null

public static void show03() {
    //创建Map集合对象
    Map<String,Integer> map = new HashMap<>();
    map.put("赵丽颖",168);
    map.put("杨逸",165);
    Integer v1 = map.get("赵丽颖");
    System.out.println("v1"+v1);//v1:165
    Integer v2 = map.get();
    System.out.println("v2"+v2);//v2:null
}

boolean containsKey(Object key)判断集合中是否包含指定的键
包含返回ture,不包含返回false

public static void show03() {
    //创建Map集合对象
    Map<String,Integer> map = new HashMap<>();
    map.put("赵丽颖",168);
    map.put("杨逸",165);
    Boolean b1 = map.containsKey("赵丽颖");
    System.out.println("b1:"+b1);//b1:true
    Boolean b2 = map.containsKey("杨怡");
    System.out.println("b2:"+b2);//b2:false
}

 

posted @ 2021-11-24 16:55  无效_rank  阅读(61)  评论(0)    收藏  举报