HashMap也是可以排序的,示例代码如下.
package com.zwy;
import java.util.SortedMap;
import java.util.TreeMap;
public class TestSortMap {
public static void main(String[] args) {
SortedMap<String, String> map = new TreeMap<String, String>();
map.put("D:长江", "1");
map.put("A:长江", "1");
map.put("C:长江", "1");
map.put("F:长江", "1");
System.out.println(map);
System.out.println(map.firstKey());
SortedMap<sKey, String> sMap = new TreeMap<sKey, String>();
sMap.put(new sKey(2), "长江");
sMap.put(new sKey(10), "长江");
sMap.put(new sKey(1), "长江");
sMap.put(new sKey(2), "长江3");
sMap.put(new sKey(6), "长江");
System.out.println(sMap);
}
}
class sKey implements Comparable{
int i ;
public sKey(int i) {
this.i = i ;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof sKey) return true;
return i > this.i;
}
@Override
public int compareTo(Object o) {
if(o instanceof sKey){
sKey key = (sKey)o;
return this.i - key.i;
} else {
return 0;
}
}
@Override
public String toString() {
return "sKey [i=" + i + "]";
}
}