import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class MapDemo { public static void main(String[] args) { Map<Integer,String> map=new HashMap<Integer,String>(); map.put(1,"Java编程思想"); map.put(2,"深入理解计算机系统"); map.put(3,"计算机网络,自顶向下方法"); map.put(4,"深入理解Java虚拟机规范"); map.put(5,"算法导论"); map.put(6,"编程珠玑"); //第一种:大家普遍使用 for(Integer key:map.keySet()){ System.out.println("key="+key+",value="+map.get(key)); } System.out.println("==============================================="); //第二种:好像这样写的人比较少见 Iterator<Map.Entry<Integer,String>> it=map.entrySet().iterator(); while(it.hasNext()){ Map.Entry<Integer,String> entry=it.next(); System.out.println("key="+entry.getKey()+",value="+entry.getValue()); } System.out.println("==============================================="); //第三种:推荐,尤其是大容量时 for(Map.Entry<Integer,String> entry:map.entrySet()){ System.out.println("key="+entry.getKey()+",value="+entry.getValue()); } System.out.println("==============================================="); //第四种:只能遍历values for(String value:map.values()){ System.out.println("value="+value); } } }