标签:collection java map 接口 集合
在上篇博文中介绍了collection集合框架,http://zyh928.blog.51cto.com/9467544/1827532
这篇博文将以一个示例介绍Map集合。
首先map和collection都是一个 接口,具体的实现都由下面的实现类实现功能。它们最大的区别就是collection是单列集合,map是双列集合(泛型参数是一个键—值对)。map集合与set类似,主要有HashMap、TreeMap和HashTable三个实现类,HashTable基本上现在不使用了。
注意:map的键(key)不可以重复,值(value)可以重复。
-map(接口)
-HashMap
-TreeMap
-HashTable
下面以HashMap为例,介绍三种获得HashMap的值
public class MapTest {
public static void main(String[] args){
HashMap<String, String> map=new HashMap<String, String>();
map.put("010", "BeiJing");
map.put("021", "ShangHai");
map.put("012", "TianJin");
map.put("043", "ChongQing");
map.put("026", "GuangZhou");
//方法一:通过map.keySet()方法得到其键
Set<String> zips=map.keySet();//得到键
Iterator<String> it=zips.iterator();
while(it.hasNext()) {
String zip=it.next();
System.out.println(zip+":"+map.get(zip));
} //方法二:通过map.values()方法得到其值
Collection<String> cities=map.values();//得到值
Iterator<String> it=cities.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
//方法三:通过map.entrySet()得到键值(即一个条目entry)
Set<Entry<String, String>> entries=map.entrySet();//得到键值对
Iterator<Entry<String, String>> it=entries.iterator();
while(it.hasNext()){
Entry<String, String> entry=it.next();
String key=entry.getKey();
String value=entry.getValue();
System.out.println(key+":"+value);
}
}可以将上面的HashMap修改为TreeMap,其他代码无需修改则可以按顺序输出。
本文出自 “John” 博客,请务必保留此出处http://zyh928.blog.51cto.com/9467544/1827704
标签:collection java map 接口 集合
原文地址:http://zyh928.blog.51cto.com/9467544/1827704