Search code examples
javagenericskey-valuetreemap

Simple generic method with TreeMap<K, V> as parameter


I'm attempting to write a generic method that iterates TreeMap entries to get a value with its key (I'm using a custom comparator to sort the map based on values and as a result have broken the get() method, but that's not the problem I'm solving here). I've got the following so far, but I'm not seeing why the symbols 'K' and 'V' are not resolved - even though they're declared on the TreeMap that is passed in.

private V forceGet(TreeMap<K, V> sortedMap, K targetKey) {

    for (Map.Entry e : sortedMap.entrySet()) {
        K key = (K) e.getKey();
        V value = (V) e.getValue();
        if (key.equals(targetKey)) {
            return value;
        }
    }
    return null;
}

I confess not being an expert on generics, so apologies if this should be obvious.


Solution

  • You need to declare the generic parameters, before the return type:

    private <K, V> V forceGet(TreeMap<K, V> sortedMap, K targetKey) { ... }