Create a Map
that can be sorted by value.
The code executes as expected, but does not compile cleanly:
public class SortableValueMap<K, V> extends LinkedHashMap<K, V> {
...
public void sortByValue() {
...
Collections.sort( list, new Comparator<Map.Entry>() {
public int compare( Map.Entry entry1, Map.Entry entry2 ) {
return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
}
});
...
The syntax for passing Comparable
as a generic parameter along to the Map.Entry<K, V>
(where V
must be Comparable
?) -- so that the (Comparable)
typecast shown in the warning can be dropped -- eludes me.
Compiler's cantankerous complaint:
SortableValueMap.java:24: warning: [unchecked] unchecked call to compareTo(T) as a member of the raw type java.lang.Comparable
return ((Comparable)entry1.getValue()).compareTo( entry2.getValue() );
How can the code be changed to compile without any warnings (without suppressing them while compiling with -Xlint:unchecked
)?
Thank you!
Declare the V
type to extend the Comparable<V>
interface. That way, you can remove the cast of the Map.Entry
objects down to (Comparable)
and use the inferred type instead:
public class SortableValueMap<K, V extends Comparable<V>>
extends LinkedHashMap<K, V> {
....
Collections.sort(list, new Comparator<Map.Entry<K, V>>() {
public int compare(Map.Entry<K, V> entry1, Map.Entry<K, V> entry2) {
return entry1.getValue().compareTo(entry2.getValue());
}
});