2

I've declared a map like this:

Map<Integer, Float> errorMap = new HashMap<> ();

and then populate it. Finally I've to sort it by value. I've written this:

ValueComparator vc = new ValueComparator(errorMap);
TreeMap<Integer, Float> sortedMap = new TreeMap<> (vc);
sortedMap.putAll(errorMap);

while ValueComparator class is this:

class ValueComparator implements Comparator<Float> {
    Map<Integer, Float> map;

    public ValueComparator(Map<Integer, Float> base) {
        this.map = base;
    }


    public int compare(Float a, Float b) {
        if(map.get(a) <= map.get(b))
            return -1;
        else
            return 1;

    }

}

The problem is that when I compile this code, it gives me this error:

incompatible types: cannot infer type arguments for TreeMap<>
    reason: inference variable K has incompatible bounds
      equality constraints: Integer
      upper bounds: Float,Object
  where K is a type-variable:
    K extends Object declared in class TreeMap

Can anyone please suggest how to handle this. I'm using Java 8.

user3139987
  • 91
  • 1
  • 4
  • 1
    Your `ValueComparator` is really _extremely_ fragile and prone to bugs. You'd be much better off using something like http://stackoverflow.com/a/2581754/869736. – Louis Wasserman Jan 14 '16 at 06:36

1 Answers1

1

In the Map declaration,

TreeMap< Integer, Float> sortedMap = new TreeMap<> (vc);

The key values are of type Integer, but while getting the values in the compare() method, you are using Float values as key. So change the type of a and b to "Integer". It should work fine.

Pooja Arora
  • 574
  • 7
  • 19