Reputation: 57
public class IdfMap<K, V> extends HashMap<K, V>{
public IdfMap() {
super();
}
public IdfMap(int initialCapacity){
super(initialCapacity);
}
public IdfMap(int initialCapacity, float loadFactor){
super(initialCapacity, loadFactor);
}
public <K, V extends Comparable<? super V>> SortedSet<Map.Entry<K, V>> entriesSortedByValues(){
SortedSet<Map.Entry<K, V>> sortedEntries = new TreeSet<>(
new Comparator<Map.Entry<K, V>>() {
@Override
public int compare(Map.Entry<K, V> e1, Map.Entry<K, V> e2){
return e2.getValue().compareTo(e1.getValue());
}
}
);
sortedEntries.addAll(this.entrySet());
return sortedEntries;
}
}
The line
sortedEntries.addAll(this.entrySet());
does not work. Why? It tells me that the method is not applicable for the given argument, which is a pretty vague error statement to understand. I would except this.entrySet() to return the set, which should in theory be usable for the addAll method.
Upvotes: 1
Views: 222
Reputation: 8338
Read the error message. It says The method addAll(Collection<? extends Map.Entry<K,V>>) in the type Set<Map.Entry<K,V>> is not applicable for the arguments
(Set<Map.Entry<K,V>>)
This is because you are mixing Maps and Sets.
Upvotes: 0
Reputation: 262494
Your method introduces its own generic type parameters, also called K
and V
, but completely different from the ones defined by the class.
As a result, within the method, K
and V
refer to something different from (hence incompatible with) the "real" types.
This is like local variables shadowing member variables. And since they have the same name, the error message becomes hard to understand.
Remove the type parameter declaration from the method, should be
public SortedSet<Map.Entry<K, V>> entriesSortedByValues(){
Upvotes: 2