1
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.

2
  • 3
    Why does your method have its own type parameters? Commented Jul 8, 2014 at 5:15
  • Java noob, thanks for the help! Commented Jul 8, 2014 at 6:09

2 Answers 2

2

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(){
Sign up to request clarification or add additional context in comments.

1 Comment

Additionally, the Comparable requirement will have to be moved to the class's type parameters, or a cast involving Comparable will need to be introduced somewhere.
0

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.

1 Comment

No, that's not the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.