Map接口

Map接口

  • 特点

  • 子接口:SortedMap

    • 实现类:

      • TreeMap implement SortedMap

      • HashMap

Map接口使用

示例代码:

/**
 * Map接口的使用
 * 特点:1.存储键值对  2.键不能重复,值可以重复  3.无序
 */
public class Demo {
    public static void main(String[] args) {
        //创建Map集合
        Map<String,Integer> map = new HashMap<>();
        //1.添加
        map.put("a",1);
        map.put("b",2);
        map.put("c",3);
        map.put("c",4);  //添加重复Key时,新的value替换旧的value
        System.out.println(map.size());
        System.out.println(map.toString());

        //2.删除
        //map.remove("a");
        System.out.println(map.size());
        System.out.println(map.toString());

        System.out.println("-----------------------");
        //3.遍历
        //3.1使用KeySet();
        //Set<String> keySet = map.keySet();  //得到一个set集合
        for (String key:map.keySet()){
            System.out.println(key+":"+map.get(key));
        }
        //3.2 使用entrySet()方法  效率高与keySet();
        //Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
        for (Map.Entry<String,Integer> entry : map.entrySet()){
            System.out.println(entry.getKey()+":"+entry.getValue());
        }

        //判断
        System.out.println(map.containsKey("a"));
        System.out.println(map.containsValue(2));
    }
}

posted @ 2020-07-08 15:51  邱大将军  阅读(108)  评论(0编辑  收藏  举报