[問題]關於comparator& Map

看板java作者時間17年前 (2008/12/29 22:36), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串1/2 (看更多)
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: 140.118.155.114

12/30 23:59, , 1F
TreeMap是會用Comparator將key做排序
12/30 23:59, 1F

01/18 15:55, , 2F
謝謝 問題已解決了^^
01/18 15:55, 2F
文章代碼(AID): #19ME1QnS (java)
文章代碼(AID): #19ME1QnS (java)