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

  • 相关阅读:
    POJ 3126 Prime Path
    POJ 2429 GCD & LCM Inverse
    POJ 2395 Out of Hay
    【Codeforces 105D】 Bag of mice
    【POJ 3071】 Football
    【POJ 2096】 Collecting Bugs
    【CQOI 2009】 余数之和
    【Codeforces 258E】 Devu and Flowers
    【SDOI 2010】 古代猪文
    【BZOJ 2982】 combination
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7347274.html
Copyright © 2011-2022 走看看