HashMap和TreeMap的遍歷
阿新 • • 發佈:2018-11-21
概述:
(1)HashMap遍歷是沒有順序的,TreeMap的遍歷是有順序的;
(2)針對Map的遍歷都要轉化成Map.Entry物件,通過方法Map.entrySet()得到該物件Set
(3)通過迭代器Iterator將Map遍歷;
(4)
詳細參考如下:
import java.util.*; import java.util.Map.Entry; public class Test { public static void main(String[] args) { //HashMap 遍歷是不按順序排列 Map map=new HashMap(); map.put("m1", "m11"); map.put("m2", "m22"); map.put("m3", "m33"); map.put("m4", "m44"); Iterator iter=map.entrySet().iterator(); while(iter.hasNext()){ Map.Entry entry=(Entry) iter.next(); String key=entry.getKey().toString(); String value=entry.getValue().toString(); System.out.println(key+"*"+value); } //TreeMap 遍歷是按順序排列 Map treemap=new TreeMap(); treemap.put("t1", "t11"); treemap.put("t2", "t22"); treemap.put("t3", "t33"); treemap.put("t4", "t44"); treemap.put("t5", "t55"); Iterator titer=treemap.entrySet().iterator(); while(titer.hasNext()){ Map.Entry ent=(Map.Entry )titer.next(); String keyt=ent.getKey().toString(); String valuet=ent.getValue().toString(); System.out.println(keyt+"*"+valuet); } } }