0

I've actually got this working from this example:

static <K,V extends Comparable<? super V>> 
        List<Entry<K, V>> entriesSortedByValues(Map<K,V> map) {

List<Entry<K,V>> sortedEntries = new ArrayList<Entry<K,V>>(map.entrySet());

Collections.sort(sortedEntries, 
        new Comparator<Entry<K,V>>() {
            @Override
            public int compare(Entry<K,V> e1, Entry<K,V> e2) {
                return e2.getValue().compareTo(e1.getValue());
            }
        }
);

return sortedEntries;
}

I found it on this site; here.

Now, I have implemented this code and it does work. I understand what's happening, for the most part. The only part of the code I don't fully understand is within the method header, specifically:

static <K,V extends Comparable<? super V>>  

If anybody could explain this part of the code to me, I'd be very grateful. Specifically why I should use super in this context.

I'm fairly new to Java so trying to get a good understanding of using different techniques rather than just throwing them into my code without really understanding what's happening.

Note: I would have commented on the original answer but I can only leave comments if I have a reputation over 50. I hope I'm not breaking any rules by posting like this!

Community
  • 1
  • 1
shakel
  • 207
  • 3
  • 13

2 Answers2

1

The idea is that V is comparable to at least other Vs, but may be comparable to other types as well -- that is, comparable to anything of a supertype of V.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
1

This line is making the method generic. You can have a generic type in either the class header or in the method declaration. In this case, the method declaration.

static <K,V extends Comparable<? super V>>  

declares a generic type K that is unbounded. This means it can be any subclass of type Object. Then it declares a second type, V, that MUST implement the Comparable interface. The Comparable implementation is also typed, and the method adds a bound to that, stating that the Comparable class should be able to compare to anything of a supertype of generic type V.

Extra Reading

christopher
  • 26,815
  • 5
  • 55
  • 89
  • Thanks, that's a really great explanation. I had mostly understood it all apart from why super was being used. Your explanation really made it clear to me why exactly it's written like that. Going to read that Java Generics link you provided too. Thanks again, much appreciated. – shakel Nov 17 '14 at 21:12