在这种情况下,TreeMap无法正确排序

时间:2013-05-10 10:35:01

标签: java sorting

HashMap复制到TreeMap

的语句序列
private Map<String,Bitmap> imageFilexx= new HashMap<String,Bitmap>();

//Assuming map has values
printMap(imageFilexx);
TreeMap<String,Bitmap> imageFilexxS;
imageFilexxS= new TreeMap<String,Bitmap>(imageFilexx);
printMap(imageFilexxS);

要在地图上方显示的功能:

public static void printMap(Map<String, Bitmap> map) {
        for (Map.Entry entry : map.entrySet()) {
            System.out.println("Key : " + entry.getKey());
        }
    }

输入:

Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p7.png  
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p1.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p5.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p3.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p11.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p9.png 

当前O / P:

Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p1.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p11.png //11 should be displayed in the last 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p3.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p5.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p7.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p9.png 

预期的O / P:

Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p1.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p3.png 
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p5.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p7.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p9.png
Key : http://myserver.com/myfolder/ImageDesc/ImageDesc%20p11.png

1 个答案:

答案 0 :(得分:6)

按字典顺序排序(default排序方法)。

您必须定义自己的natural sort order实现。 TreeMap的构造函数允许您传入自定义比较器。