Priority queue for a HashMap object in Java

I created a HashMap object that stores the String as key and the corresponding value as int. Now I want to have a priority queue that has all the String present in the HashMap object with a value as a reference to assign priorities. I wrote 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 indicates an error; cannot type the argument for the priority queue. Please explain to me what mistake I made.

+6
source share
1 answer

The error you are referring to states is that it cannot guess the parameter of the generic type that you omitted. The reason for this is because the constructor you are using is unknown. This is unknown because the second argument is not a comparator. Your comparator must implement the java.util.Comparator interface in order to be safe for the constructor to accept.

 public class TComparator<String> implements Comparator<String> { @Override public int compare(String arg0, String arg1) { // ... } } 

Also note: in the Comparator interface, the corresponding method is called compare , not compareTo .

General advice, I have to agree with Louis Wasserman, for the two arguments given, the comparator should always return the same result and not depend on the state of the application. It’s too easy not to think about a case, and the application is ultimately messed up.

+3
source

Source: https://habr.com/ru/post/926163/


All Articles