作者ogamenewbie (._.)
看板java
标题Re: [问题]关於comparator& Map
时间Mon Dec 29 22:43:46 2008
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