I have created a HashMap object which stores a String as key and corresponding value as int. Now I want to have a Priority Queue which have all the String present in HashMap object with value as reference for assigning priorities. I have written the following code
public class URIQueue {
private HashMap<String,Integer> CopyQURI;
private PriorityQueue<String> QURI;
public class TComparator<String> {
public int compareTo(String s1, String s2) {
if (CopyQURI.get(s2) - CopyQURI.get(s1) >= 0) {
return 1;
} else {
return 0;
}
}
}
public URIQueue() {
CopyQURI=new HashMap<>(100);
TComparator<String> tc=new TComparator<>();
QURI=new PriorityQueue<>(100, tc); //Line x
}
}
Line x is showing error cannot infer type argument for priority queue. Please guide me what mistake I have done.
The error you are referring to states, that it cannot guess the generic type parameter which you have omitted. The reason for that is that the constructor you are using is not known. It is not known, because you second argument is not a comparator. Your comparator has to implement the java.util.Comparator interface in order to be type safe for the constructor to accept.
Also mind, in the
Comparatorinterface the appropriate method is calledcompareand notcompareTo.A general advice, I have to agree with Louis Wasserman, for two given arguments a comparator should always return the same result and not depend on the state of the application. It’s just too easy not to think of some case and the application is eventually flawed.