本帖最后由 李金中 于 2014-2-20 16:03 编辑
public class TreeMapTest {
public static void main(String[] args)
{
TreeMap<String, Integer> tr = new TreeMap();
tr.put("a", 3);
tr.put("b", 5);
tr.put("c", 4);
tr.put("d", 2);
Set<Map.Entry<String, Integer>> setMap = tr.entrySet();
//打印按键排序的结界
for(Map.Entry temp : setMap)
{
System.out.println(temp.getKey() + ":" + temp.getValue());
}
System.out.println("=================");
int size = tr.size();
MapSort<String, Integer>[] mapSortArr = new MapSort[size];
int index = 0;
for(Map.Entry<String, Integer> temp : setMap)
{
mapSortArr[index] = new MapSort(temp.getKey(), temp.getValue());
index++;
}
//对值进行插入排序
for(index = 1; index < size; index++)
{
int i = index - 1;
Integer keyVal = mapSortArr[index].val;
String keyString = mapSortArr[index].key;
while((i >= 0) && ((mapSortArr.val).compareTo(keyVal) == 1))
{
mapSortArr[i + 1].key = mapSortArr.key;
mapSortArr[i + 1].val = mapSortArr.val;
i--;
}
mapSortArr[i + 1].key = keyString;
mapSortArr[i + 1].val = keyVal;
}
//打印按值排序后的结果。
for(MapSort mTemp : mapSortArr)
{
System.out.println(mTemp.key + ":" + mTemp.val);
}
}
}
class MapSort<K, V>
{
public K key;
public V val;
MapSort(K key, V val)
{
this.key = key;
this.val = val;
}
}
稍微实现了下,我觉得值得考虑,就试着写了下,看看OK不。
|