I am new in Java. I am implementing Comparator interface & i am having a compareTo function below:-
public int compare(Object o1, Object o2) {
Map.Entry e1 = (Map.Entry) o1;
Map.Entry e2 = (Map.Entry) o2;
return ((Comparable) e1.getValue()).compareTo(e2.getValue());
}
I am not be able to understand what does this line means
Map.Entry e1 = (Map.Entry) o1;
What is the use of two Map.Entry
??
Why Comparable
in type casting ??
Someone please give me a reference so that i can figure it out. Thanks.
Edited:- Here is my whole class,i am having a HashMap I want to sort by values using Generic class,hence writing this class
package via;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class SortMap<K, V> {
public Map<K, V> getSortedMap(Map<K, V> mapToSort) {
List<Map.Entry> list = new ArrayList<Map.Entry>(mapToSort.entrySet());
Collections.sort(list, new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Map.Entry e1 = (Map.Entry) o1;
Map.Entry e2 = (Map.Entry) o2;
return ((Comparable) e2.getValue()).compareTo(e1.getValue());
}
});
Map sortedMap = new LinkedHashMap();
for(Iterator i=list.iterator();i.hasNext();)
{
Map.Entry entry=(Map.Entry)i.next();
sortedMap.put(entry.getKey(), entry.getValue());
}
System.out.println(list);
return sortedMap;
}
}