比如以下代码输出结果为
Entry collection is :
2=Chenar
1=Vida
3=Lillian
如何才能让输出为
Entry collection is :
1=Vida
2=Chenar
3=Lillian谢谢啦~!!
--------------------------------------------------------------------------
import java.util.*;
class HashMapTest
{
     public static void printAllElement(Collection co
     {
Iterator it=co.iterator();
while(it.hasNext())
{
   System.out.println(it.next()); 
}
     }

     public static void main(String[] args)
     {
HashMap<Integer, Object> hm=new HashMap<Integer, Object>();
hm.put(1, "Vida");
hm.put(2, "Chenar");
hm.put(3, "Lillian");

Set s2=hm.entrySet();
System.out.println("Entry collection is :");
printAllElement(s2);

      }
}

解决方案 »

  1.   

    楼主首先要搞清楚,Map是不排序的。用 iterator 输出来的顺序其实是假象。要想按照key的顺序输出 Map 的值,首先要取出 keyset,然后将其转化成 Array,接着使用 Arrays.sort() 进行排序,这样就可以用 Map 的 get 方法按顺序取出值了:import java.util.Arrays;
    import java.util.HashMap;public class ShowMapWithSortedKeys {    /**
         * @param args
         */
        public static void main(String[] args) {
            HashMap map = new HashMap();
            map.put("3", "Orange");
            map.put("1", "Apple");
            map.put("2", "Banana");        String[] keys = (String[]) map.keySet().toArray(new String[map.size()]);
            Arrays.sort(keys);        for (int i = 0; i < keys.length; i++) {
                System.out.println("map[\"" + keys[i] + "\"] = \"" + map.get(keys[i]) + "\"");
            }
        }}
      

  2.   

    要想对key排序用treeMap,放一个comparator进去,自己去实现里面的compare方法,HashMap是为了快速查找所设计的map,用的是hash算法,根据hashcode来排的位.