一.摘要
Map是一个键和值的集合数据结构,每一个键映射唯一的值,在声明Map对象时需要同时声明用作键的对象类。一个Map提供有用的方法遍历包含的所有键,以及各种方法访问和更新键、值对。
二.方法解析
1.clear()
从Map移除所有的元素,置空集合
- mMap.clear();
2.containsKey(Object key)
当前Map包含指定的键,返回true
- boolean isContained=mMap.containsKey(key);
3.containsValue(Object val)
当前Map包含指定的值,返回true
- boolean isContained=mMap.containsValue(value);
4.equals(Map map)
当前Map和指定的Map包含相同的映射关系,返回true
- /**
- *相同的元素个数,键、值一致,返回true
- *
- */
- Map map=new HashMap();
- map.put("id", new Integer(123456789));
- Map map2=new HashMap();
- map2.put("id", new Integer(123456789));
- System.out.println(map.equals(map2));
- /**
- *不同的元素个数,返回false
- *
- */
- Map map=new HashMap();
- map.put("id", new Integer(123456789));
- Map map2=new HashMap();
- map2.put("id", new Integer(123456789));
- map2.put("token_id", new Integer(123456789));
- System.out.println(map.equals(map2));
- /**
- *相同的元素个数,键一致,值不一致,返回false
- *
- */
- Map map=new HashMap();
- map.put("id", new Integer(12345));
- Map map2=new HashMap();
- map2.put("id", new Integer(123456789));
- System.out.println(map.equals(map2));
- /**
- *相同的元素个数,值一致,键不一致,返回false
- *
- */
- Map map=new HashMap();
- map.put("id", new Integer(123456789));
- Map map2=new HashMap();
- map2.put("token_id", new Integer(123456789));
- System.out.println(map.equals(map2));
5.get(Object key)
Map根据键获取值,直接通过指定一个对象的key获取,也可以返回key的集合Set,遍历所有的键、值
- Integer value=(Integer)map.get("id");
- System.out.println(value);
- /**
- *遍历Map集合
- *
- */
- Set keySet = map.keySet();
- Iterator iter = keySet.iterator();
- while (iter.hasNext()) {
- String key = (String)iter.next();
- System.out.println(key+"="+map.get(key));
- }
6.keySet()
返回键的Set集合
- /**
- *返回Set集合
- *
- */
- Set keySet = map.keySet();
6.entrySet()
返回映射关系的Set集合
- /**
- *返回Set集合
- *
- */
- Set<Entry<String,Integer>> mappingSet = map.entrySet();
- Iterator iter=mappingSet.iterator();
- while(iter.hasNext()){
- Entry<String, Integer> entry=(Entry<String, Integer>) iter.next();
- String key=entry.getKey();
- Integer val=entry.getValue();
- System.out.println(key+"="+val);
- }
7.isEmpty()
当前Map为空,返回false
- boolean isEmpty=map.isEmpty();
8.put(Object key,Object value)
存储键值对到当前Map集合
- map.put("id", new Integer(123456789));
9.putAll(Map map)
将另一个Map集合的键值对复制到当前Map
- /**
- * 将另一个Map集合的键值对复制到当前Map
- */
- ap.putAll(map2);
10.remove(Object key)
删除指定键的映射关系
- /**
- * 删除指定键的映射关系
- */
- map.remove("id");
11.size()
返回当前Map集合的大小
- /**
- * 返回当前Map集合的大小
- */
- map.size();
12.values()
返回Map包含的值的Collection集合
- /**
- * 返回Map包含的值的Collection
- */
- Collection collection=map.values();
- Iterator iter=collection.iterator();
- while(iter.hasNext()){
- Integer entry=(Integer) iter.next();
- System.out.println(entry);
- }
你可能感兴趣的文章
来源:TeachCourse,
每周一次,深入学习Android教程,关注(QQ158#9359$239或公众号TeachCourse)
转载请注明出处: https://www.teachcourse.cn/1834.html ,谢谢支持!
转载请注明出处: https://www.teachcourse.cn/1834.html ,谢谢支持!