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.

asked Jan 14, 2016 at 6:10
1
  • 1
    Your ValueComparator is really extremely fragile and prone to bugs. You'd be much better off using something like stackoverflow.com/a/2581754/869736. Commented Jan 14, 2016 at 6:36

1 Answer 1

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.

answered Jan 14, 2016 at 6:27
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.