码迷,mamicode.com
首页 > 编程语言 > 详细

Java 中 Map 的使用

时间:2015-07-25 21:38:45      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:java   map   hashmap   

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

版权声明:本文为博主原创文章,未经博主允许不得转载。

Java 中 Map 的使用

标签:java   map   hashmap   

原文地址:http://blog.csdn.net/shf4715/article/details/47059425

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!