Map的遍历方法:
1、使用entrySet()返回一个Set集合
2、创建Set集合的Iterator迭代器
3、利用迭代器获得Map.Entry类型的对象
4、利用(Static)Map.Entry的getKey()和getValue()方法获取值
代码如下:
import java.util.*;
public class AnswerTo12{
public static void main(String args[]){
Map<String,String> mp=new HashMap<String,String>();
mp.put("Tom","CoreJava");
mp.put("John","Oralce");
mp.put("Susan","Oracle");
mp.put("Jerry","JDBC");
mp.put("Jim","Unix");
mp.put("Kevin","Jsp");
mp.put("Lucy","jsp");
mp.put("Allen","JDBC");//增加一个老师
mp.put("Lucy","CoreJava");//更换Lucy的课程
Set entry=mp.entrySet();
Iterator itor=entry.iterator();
while(itor.hasNext()){
Map.Entry mn=(Map.Entry)itor.next();//这里的强制转换必须有。不然返回默认是object类型
System.out.println(mn.getKey()+" "+mn.getValue());
}
}
}