JAVA集合:Map集合

Collection接口和Map接口没有任何继承关第,Map与Collection不同在于,Map存储的是键值对key-value

Map的特点:

1. Collection中的元素,元素是孤立存在的,而Map中的元素都是key-value成对存在的,一个键映射一个值。

2. 键是不能重复的,值可以重复

3. Map中常用的集合有HashMap LinkedHashMap

Map<K,V> K V表示键和值的数据类型,如Map<String,Integer>

二、HashMap<K,V>和LinkedHashMap<K,V>

HashMap<K,V> 存储数据采用哈希表结构,元素的存取顺序不能保证一致,由于要保证键的唯一 不重复,需要重写hashCode() 、equals()方法

HashMap<K,V>下面有个子类LinkedHashMap<K,V>,存储数据采用的是哈希表结构+链表结构,通过链表结构可以保证元素的存取顺序一致,通过哈希表结构可以保证键的唯一 不重复,需要重写hashCode() 方法和equals()方法

注意: Map接口中的集合都有两个泛型<K,V>,在使用时,要为两个泛型变量赋予数据类型,两个泛型变量<K,V>的数据类型可以相同,也可以不同。

三、Map接口中的常用方法

1. put(k,v); 向集合中存储键值对

Map<String,Integer> map = new HashMap<String,Integer>();

map.put("a",10);

map.put("b",20);

注意:当存入重复键时,后存的将原有的覆盖掉。

返回值:一般情况下返回null,有覆盖重复键时,返回值为被覆盖元素的值。

2. get(K); 获取指定键名映射的值

Map<String,Integer> map = new HashMap<String,Integer>();

map.put("a",10);

map.put("b",20);

map.put("c",30);

int i = map.get("a"); //获取键名为"a"所映射的值,结果为10

注意:如果集合中不存的此键名,则返回null

3. remove(K); 移除指定键名所映射的值,移除键值对

Map<String,Integer> map = new HashMap<String,Integer>();

map.put("a",10);

map.put("b",20);

map.put("c",30);

map.remove("a"); //移除键名为"a"的键值对

返回值:移除之前元素的值。如果不存在这个键名,则返回null

三、Map集合的遍历

Map集合是没有办法直接遍历的,须通过set集合来遍历

方法:keySet(); 通过keySet()方法,将Map集合中所有键,放到一个Set集合中去

Map<String,Integer> map = new HashMap<String,Integer>();

map.put("a",10);

map.put("b",20);

map.put("c",30);

//利用keySet();方法得到键的set集合

Set<String> set = map.keySet();

1. 用增强for遍历

for(String key: set){

  Integer value = map.get(key);

}

2. 用迭代器遍历

Iterator<String> it = set.iterator();

while(it.hasNext()){

  String key = it.next();

  Integer value = map.get(key);

}

 

posted on 2018-06-19 14:37  adamal  阅读(131)  评论(0)    收藏  举报