I've got a hashmap<CustomObject,Integer>
and I'd like to compare the Integers (values) within each entry. So, basically I'd like to sort my values by their Integer
value in descending order. I've got a Comparator
which consists of the following...
class Compare implements Comparator<Integer>{
Map<CustomObject,Integer> map;
/**
* Constructs our map
* @param map map to be sorted.
*/
public Compare(Map<CustomObject,Integer> map){
this.map = map;
}
/**
* Performs the comparison between two entries.
*/
public int compare(Integer one, Integer two){
if(map.get(one) <= map.get(two)){
return 1;
}else{
return 0;
}
}
}
I pass my Hashmap
into the TreeMap by calling the following line of code.. Tmap.putAll(Hmap);
. Where Tmap and Hmap are defined as:
private HashMap<CustomObject,Integer> Hmap;
private TreeMap<CustomObject,Integer> Tmap;
When I run my code I get the error Exception in thread "main" java.lang.ClassCastException: CustomObject cannot be cast to java.lang.Comparable
.
The exception appears to be called when I attemp to extract a value from my sorted list. like so...
TreeMap<CustomObject,Integer> sorted = Tmap.putAll(hmap);
sorted.get(o);
where o
is a CustomObject.
I think I've misunderstood how comparator works.. what am I doing wrong? How would I compare the two Integer values?
EDIT
Just to clarify what I'm actually trying to do...
I want to compare Integers which are linked to a CustomObject. I can't make the key the Integer because these Integers may not be unique. I was to compare them because I'd like to sort my collection in descending order based on their Integer value.