向 TreeMap<String, Integer> 插入鍵 "1"、"2"..."10"..."20" 後,遍歷順序為:{1=0, 10=0, 11=0, 2=0, 20=0...},並非預期的數值順序。
TreeMap 默認按 Key 的自然順序排序。String 類型按字典序比較,故 "10" < "2"。
Map<Integer, Integer> map = new TreeMap<>();
map.put(1, 0);
map.put(10, 0);
// 遍歷順序即為 1, 2, 3...10, 11...
Map<String, Integer> map = new TreeMap<>((a, b) -> {
try {
return Integer.compare(Integer.parseInt(a), Integer.parseInt(b));
} catch (NumberFormatException e) {
return a.compareTo(b); // 非數字字符串回退字典序
}
});
若 Key 代表數值,優先使用數值類型;必須用字符串時,提供數值解析的 Comparator。