我有一段代碼,我試圖按照降序排列TreeMap
中的密鑰,因爲當我只使用TreeMap
時,它會根據按升序排列的鍵進行排序。我得到的錯誤是:如何自定義TreeMap以按降序對鍵進行排序?
沒有適用於TreeMap的構造函數。
這裏有什麼問題?
import java.util.TreeMap;
import java.util.Map;
import java.util.Comparator;
import java.util.Map.Entry;
import java.util.SortedMap;
public class ChangeMachine {
public TreeMap<Double, Integer> dispenseChange(Double changeAmount, TreeMap<Double, Integer> coinsMap) {
TreeMap<Double, Integer> coinDispenserMap = new TreeMap<>();
for (Map.Entry<Double, Integer> coin : coinsMap.entrySet()) {
if (!(changeAmount > coin.getKey())) {
coinDispenserMap.put(coin.getKey(), 0);
continue;
}
int noOfCoins = (int) (changeAmount/coin.getKey());
coinDispenserMap.put(coin.getKey(), noOfCoins);
Double remainder = changeAmount % coin.getKey();
changeAmount = remainder;
if (changeAmount == 0.0) {
break;
}
}
return coinDispenserMap;
}
public static void main(String[] args) {
ChangeMachine ref = new ChangeMachine();
TreeMap<Double, Integer> coinsMap = new TreeMap<Double, Integer>(new Comparator<Entry<Double, Integer>>() {
public int compare(Entry<Double, Integer> coin1, Entry<Double, Integer> coin2) {
return (coin2.getKey().compareTo(coin1.getKey()));
}
});
coinsMap.put(0.25, 10);
coinsMap.put(0.01, 10);
coinsMap.put(0.05, 10);
coinsMap.put(0.10, 10);
TreeMap<Double, Integer> coinDispenserMap = ref.dispenseChange(0.86, coinsMap);
for (Map.Entry<Double, Integer> coin : coinDispenserMap.entrySet()) {
System.out.println(coin.getKey() + " : " + coin.getValue());
}
}
}
您需要比較'雙',而不是'<條目<雙整數>>' –
謝謝。有用!! – Sekhar