看板 java 關於我們 聯絡資訊
TreeMap public TreeMap(Comparator c) Constructs a new, empty map, sorted according to the given comparator. All keys inserted into the map must be mutually comparable by the given comparator: comparator.compare(k1, k2) must not throw a ClassCastException for any keys k1 and k2 in the map. If the user attempts to put a key into the map that violates this constraint, the put(Object key, Object value) call will throw a ClassCastException. Parameters: c - the comparator that will be used to sort this map. A null value indicates that the keys' natural ordering should be used. ※ 引述《jojoharebell ()》之銘言: : Map<String , Integer> items : = new TreeMap<String,Integer>(new myComparator()); : 我自己建了個class myaComparator : 準備排序TreeMap : 可是在黃色的地方卻出錯了 : public class myComparator implements Comparator{ : public int compare(Object o1, Object o2) { : Map.Entry e1 = ( Map.Entry) o1; : ---> Map.Entry e2 = ( Map.Entry) o2; : Integer d1 = (Integer) e1.getValue(); : Integer d2 = (Integer) e2.getValue(); : if(d1>=d2) : return 1; : else : return -1; : } : } : 錯誤訊息如下: : Exception in thread "main" java.lang.ClassCastException: java.lang.String : cannot be cast to java.util.Map$Entry : at myComparator.compare(myComparator.java:7) : at java.util.TreeMap.getEntryUsingComparator(Unknown Source) : at java.util.TreeMap.getEntry(Unknown Source) : at java.util.TreeMap.containsKey(Unknown Source) : at Fptree.processItems(Fptree.java:45) : at test.main(test.java:13) : 請問是哪裡有問題呢? : 謝謝 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 218.160.33.177