public class Testing {
public static void main(String[] args) {
HashMap<String,Double> map = new HashMap<String,Double>();
ValueComparator bvc = new ValueComparator(map);
TreeMap<String,Double> sorted_map = new TreeMap<String,Double>(bvc);
sorted_map.putAll(map);
}
}
class ValueComparator implements Comparator<String> {
Map<String, Double> base;
public ValueComparator(Map<String, Double> base) {
this.base = base;
}
// Note: this comparator imposes orderings that are inconsistent with equals.
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
} // returning 0 would merge keys
}
}
1 回答

弒天下
TA貢獻1818條經驗 獲得超8個贊
sorted_map在初始化的時候,你給了它Comparator, 所以sorted_map.putAll(map)的時候,實際上是把map里的每個entry放進sorted_map里,每放一個,sorted_map就會調用Comparator的compare方法來比較一下,決定放在哪個位置,這樣sorted_map的entry就都是按照Comparator的順序規(guī)則來排列的啦。
添加回答
舉報
0/150
提交
取消