Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric method to Sort a Map on Values
    text
    copied!<p>I have a small program that is supposed to sort a map based on its values. Here is what I have so far:</p> <pre><code> public static &lt;K, V extends Comparable&lt; ? extends V&gt;&gt; Map&lt;K, V&gt; sortByValues(final Map &lt;K, V&gt; mapToSort) { List&lt;Map.Entry&lt;K, V&gt;&gt; entries = new ArrayList&lt;Map.Entry&lt;K, V&gt;&gt;(mapToSort.size()); entries.addAll(mapToSort.entrySet()); Collections.sort(entries, new Comparator&lt;Map.Entry&lt;K, V&gt;&gt;() { public int compare( final Map.Entry&lt;K, V&gt; entry1, final Map.Entry&lt;K, V&gt; entry2) { return entry1.getValue().compareTo(entry2.getValue()); } }); Map&lt;K, V&gt; sortedMap = new LinkedHashMap&lt;K, V&gt;(); for (Map.Entry&lt;K, V&gt; entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); } return sortedMap; } </code></pre> <p>I want my generic value V to be comparable to anything that is <strong>either V or is a at least a subclass of V</strong>. </p> <p>I get the following error for the code piece :</p> <pre><code>public static &lt;K, V extends Comparable&lt; ? extends V&gt;&gt; </code></pre> <blockquote> <p>Bound mismatch: The method compareTo(? extends V) of type V is not applicable for the arguments (V). The wildcard parameter ? extends V has no lower bound, and may actually be more restrictive than argument V</p> </blockquote> <p><strong>How can it be more restrictive?</strong></p> <p>If I change the declaration to:</p> <pre><code>public static &lt;K, V extends Comparable&lt; ? super V&gt;&gt; </code></pre> <p>then there is no error. But this is not what I want.</p> <p>One workaround I have is that, I can change the declaration to:</p> <pre><code>public static &lt;K, V extends Comparable&lt;V&gt;&gt; </code></pre> <p>but doing this I lose the flexibility in that I cannot pass a Map whose value implements Comparable with a subclass of itself.</p> <p>Apologies for such a long question. Thanks in advance.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload