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 Answer 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
lang-java
ValueComparator
is really extremely fragile and prone to bugs. You'd be much better off using something like stackoverflow.com/a/2581754/869736.