2

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.

Geyser14
  • 1,385
  • 3
  • 14
  • 32
  • 3
    Your method is not generic. Here's the tutorial on [Generic Methods](https://docs.oracle.com/javase/tutorial/extra/generics/methods.html) – Sotirios Delimanolis Mar 27 '15 at 18:28
  • Also read [What is a raw type and why shouldn't we use it?](http://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Sotirios Delimanolis Mar 27 '15 at 18:33
  • I know your question was about generics, but are you sure that iterating over the entry set will even work if you've broken the `TreeMap`? – Paul Boddington Mar 27 '15 at 18:38
  • Yes that works - the TreeMap keys and values are all intact, but apparently the get() method uses the same custom comparator that I created for my value sort. – Geyser14 Mar 27 '15 at 18:47

2 Answers2

7

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

private <K, V> V forceGet(TreeMap<K, V> sortedMap, K targetKey) { ... }
Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
0

I think you have to declare K and V in your function:

private <K,V> V forceGet(...)
{
       //your code
}
fonfonx
  • 1,475
  • 21
  • 30