zoukankan      html  css  js  c++  java
  • Java 中 Map 的使用

    Map接口提供了一组能够以键-值对(key,value)形式存储的数据结构。


    Map对存入元素仅仅有一个要求。就是键(key)不能反复,Map对于key。value要求不是非常严格,key仅仅要是引用类型就可以。

    通常情况下,使用String和Integer比較多。

    Map提供了一个方法用来存入数据:
    V put(K k,V v)
    该方法的作用是将key-value对存入Map中。由于Map中不同意出现反复的key,所以若当次存入的key已经在Map中存在,则是替换value操作。而返回值则为被替换的元素。若此key不存在,那么返回值为null。
    Map提供了一个获取value的方法
    V get(Object key)
    该方法的作用就是依据给定的key去查找Map中相应的value并返回,若当前Map中不包括给定的key,那么返回值为null。
    Map中的containsKey方法用于检測当前Map中是否包括给定的key。其方法定义例如以下:
    boolean containsKey(Object key)

    public class HashMapDemo {
        public static void main(String[] args) {
            Map<String, Integer> hashMap = new HashMap<String,Integer>();
            hashMap.put("one", 1);
            hashMap.put("two", 2);
            hashMap.put("three", 3);
            hashMap.put("four", 4);
            hashMap.put("five", 5); 
            hashMap.put("six", null);
    
            //获取Map中key为two所相应的value
            Integer two = hashMap.get("two");
            Integer other = hashMap.get("other");
            System.out.println(two);
            System.out.println(other);
            //检查Map中是否有相应的key
            boolean getTwo = hashMap.containsKey("two");
            boolean getOther = hashMap.containsKey("other");
            System.out.println(getTwo);
            System.out.println(getOther);
    
        }
    }

    执行结果:
    2
    null
    true
    false

  • 相关阅读:
    leetcode-----5. 最长回文子串
    leetcode-----4. 寻找两个正序数组的中位数
    leetcode-----3. 无重复字符的最长子串
    leetcode-----2. 两数相加
    leetcode-----1. 两数之和
    leetcode-----第 26 场双周赛
    leetcode-----104. 二叉树的最大深度
    leetcode-----103. 二叉树的锯齿形层次遍历
    leetcode-----102. 二叉树的层序遍历
    数据管理必看!Kendo UI for jQuery过滤器的全球化
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7347274.html
Copyright © 2011-2022 走看看