您的位置:首页 > 编程语言 > Java开发

Java 中 Map 的使用

2015-07-25 19:53 525 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: