Map接口中常用的方法

package cn.itcast.day12.demo03;

import java.util.HashMap;
import java.util.Map;

/**
 * @author admin
 * @version 1.0.0
 * @ClassName Demo03.java
 * @Description TODO
 * @createTime 2021年09月25日 14:41:00
 */

public class Demo03 {
    public static void main(String[] args) {
        show3();
    }

    /**
     * boolean containsKey (Object key) 判断集合中是否包含指定的键
     * 包含返回true 不包含false
     *
     */
    private static void show3() {
        //创建集合对象
        HashMap<String, Integer> map = new HashMap<>();
        map.put("赵丽颖",168);
        map.put("杨颖",165);
        map.put("林志玲",188);

        boolean b1 = map.containsKey("杨颖");
        System.out.println("b1 = " + b1);//b1 = true
        boolean b2 = map.containsKey("洋洋");
        System.out.println("b2 = " + b2);//b2 = false

    }

    /**
     *public V get (Object key) 根据指定的键 在Map集合中获取对应的值
     *  返回值:
     *      key存在 返回对应的value值
     *      key不存在 返回的是null
     *
     */
    private static void show2() {
        //创建集合对象
        HashMap<String, Integer> map = new HashMap<>();
        map.put("赵丽颖",168);
        map.put("杨颖",165);
        map.put("林志玲",188);

        Integer v = map.get("杨颖");
        System.out.println("v = " + v);//v = 165
        Integer v2 = map.get("杨洋");
        System.out.println("v2 = " + v2);//v2 = null
    }

    /**
     * public V remove(Object,key):把指定的键 所对应的健值对儿元素 在Map集合中删除 返回被删除元素的值
     *  返回值:V
     *      key存在,V返回被删除的值
     *      key不存在,V返回null
     *
     */
    private static void show1() {
        //创建集合对象
        HashMap<String, Integer> map = new HashMap<>();
        map.put("李白",168);
        map.put("猴子",178);
        map.put("韩信",188);
        System.out.println(map);//{猴子=178, 李白=168, 韩信=188}

        Integer v = map.remove("韩信");
        System.out.println("v = " + v);//v = 188
        System.out.println(map);//{猴子=178, 李白=168}
        Integer v2 = map.remove("憨憨");
        //int v2 = map.remove("憨憨");//自动拆箱 NullPointerException异常 因为返回值是null 所以int接收不合适
        //在以后的开发中尽可能多使用Interger
        System.out.println("v2 = " + v2);//v2 = null


    }

    /**
     *public V put<k,v>:把指定的键与指定的值添加到Map集合中。
     *  返回值:V
     *      存储健值对儿的时候,key不重复,返回值V是null
     *      存储键值对儿的时候,key重复,会使用新的value替换map中重复的value,返回被替换的value值
     *
     */
    private static void show() {
        //创建Map集合对象,多态
        HashMap<String, String> map = new HashMap<>();
        String v = map.put("刘备", "孙尚香1");
        System.out.println("v = " + v);//v = null
        String v1 = map.put("刘备", "孙尚香2");
        System.out.println("v1 = " + v1);//v1 = 孙尚香1
        System.out.println(map);//{刘备=孙尚香2}
        System.out.println("================");
        map.put("吕布","貂蝉");
        map.put("周瑜","小乔");
        map.put("孙权","大乔");
        System.out.println(map);//{孙权=大乔, 吕布=貂蝉, 刘备=孙尚香2, 周瑜=小乔}
    }
}

おすすめ

転載: blog.csdn.net/nanyangnongye/article/details/120472023
おすすめ