java:Map借口及其子类HashMap二
重点:所有的集合必须依赖Iterator输出
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("zhangsan", 1); map.put("lisi", 2); map.put("zhangsan", 3); map.put("wangwu", 4); map.put("tianqi", 5); //获取数据,存放set //如果用list<string>接受不可用。报错。 Set<String> keys = map.keySet(); Iterator<String> iter = keys.iterator(); //输出 while(iter.hasNext()) { System.out.print( iter.next() + "、"); } System.out.println(keys);
结果:
lisi、zhangsan、wangwu、tianqi、 [lisi, zhangsan, wangwu, tianqi]
获取value内容:Map.get(key);
Map<String,Integer> allMap = new HashMap<String, Integer>(); allMap.put("zhangsan", 1); allMap.put("zhangsan", 2); allMap.put("lisi", 3); allMap.put("tianqi", 4); Integer value = allMap.get("zhangsan"); System.out.println(value);
结果:2
Map<String, Integer> map = new HashMap<String, Integer>(); map.put("zhangsan", 1); map.put("lisi", 2); map.put("zhangsan", 3); map.put("wangwu", 4); map.put("tianqi", 5); //获取数据,存放set //如果用list<string>接受不可用。报错。 Set<String> keys = map.keySet(); Iterator<String> iter = keys.iterator(); //输出 while(iter.hasNext()) { String key = iter.next(); System.out.println( key + " --> " + map.get(key) + "、"); } System.out.println(keys);
输出内容:
lisi --> 2、 zhangsan --> 3、 wangwu --> 4、 tianqi --> 5、 [lisi, zhangsan, wangwu, tianqi]