import java.util.HashMap;import java.util.Iterator;import java.util.Map;import java.util.Map.Entry;import java.util.Set;publicclassMapTest{privateMap<String,String> map;publicMapTest(){
map =newHashMap<String,String>();
map.put("1","第一個(gè)數(shù)");
map.put("2","第二個(gè)數(shù)");
map.put("3","第三個(gè)數(shù)");}// 第一種方法(傳統(tǒng)方法)publicvoid mapOne(){Set<String> set = map.keySet();Iterator<String> it = set.iterator();while(it.hasNext()){String key =(String) it.next();String value =(String) map.get(key);System.out.println(key +"="+ value);}}// 第二種方法(傳統(tǒng)方法)publicvoid mapTwo(){Set set = map.entrySet();Iterator it = set.iterator();while(it.hasNext()){Entry entry =(Entry) it.next();String key =(String) entry.getKey();String value =(String) entry.getValue();System.out.println(key +"="+ value);}}// 第三種方法(增強(qiáng)for循環(huán)方法)publicvoid mapThree(){for(Object obj : map.keySet()){String key =(String) obj;String value =(String) map.get(key);System.out.println(key +"="+ value);}}// 第四種方法(增強(qiáng)for循環(huán)方法)publicvoid mapFour(){for(Object obj : map.entrySet()){Entry entry =(Entry) obj;String key =(String) entry.getKey();String value =(String) entry.getValue();System.out.println(key +"="+ value);}}publicstaticvoid main(String[] args){MapTest mapTest =newMapTest();System.out.println("=====first=====");
mapTest.mapOne();System.out.println("=====second=====");
mapTest.mapTwo();System.out.println("=====three=====");
mapTest.mapThree();System.out.println("=====four=====");
mapTest.mapFour();}}輸出結(jié)果:
=====first=====3=第三個(gè)數(shù)2=第二個(gè)數(shù)1=第一個(gè)數(shù)=====second=====3=第三個(gè)數(shù)2=第二個(gè)數(shù)1=第一個(gè)數(shù)=====three=====3=第三個(gè)數(shù)2=第二個(gè)數(shù)1=第一個(gè)數(shù)=====four=====3=第三個(gè)數(shù)2=第二個(gè)數(shù)1=第一個(gè)數(shù)