I am getting confused on the PriorityQueue, not sure if there is a different method for my use case.
Instead of comparing two Strings, I want to compare the incoming Strings against a String[].
It somewhat works but the head node does not move.
Main:
public class App
{
public static void main( String[] args )
{
PriorityString priorityString = new PriorityString();
PriorityQueue<String> priorityQueue = new PriorityQueue<String>(priorityString);
priorityQueue.add("test");
priorityQueue.add("john");
priorityQueue.add("blue");
priorityQueue.add("orange");
priorityQueue.add("grape");
priorityQueue.add("handle");
while (!priorityQueue.isEmpty()) {
System.out.println("Removed: " + priorityQueue.remove());
}
}
}
Comparator class:
public class PriorityString implements Comparator<String> {
String[] valueStrings;
PriorityString() {
valueStrings = new String[] {"all", "john", "door", "floor", "record", "desk", "orange"};
}
public int compare(String o1, String o2) {
if (Arrays.asList(valueStrings).contains(o1))
return 0;
else
return 1;
}
}
Result:
Removed: test
Removed: john
Removed: orange
Removed: blue
Removed: handle
Removed: grape
The values 'test' comes first all the time even though it is not in the String[]. The other values seem to be in the correct order since 'john' and 'orange' are in the String[] and the rest is not.
What is the issue and is this the right way to implement my use case?
Edit: I have also tried this
public int compare(String o1, String o2) {
if (Arrays.asList(valueStrings).contains(o1))
return -1;
else if (Arrays.asList(valueStrings).contains(o2))
return 0;
else
return 1;
}
Which gives this result:
Removed: orange
Removed: handle
Removed: grape
Removed: test
Removed: blue
Removed: john
orange is in the right place by john is at the bottom when it should be right after orange
New Edit: after rereading the doc as per the comment, I managed to get a working version implemented in this way. Probably will add @Progman else return.
public int compare(String o1, String o2) {
if (Arrays.asList(valueStrings).contains(o1))
return -1;
else if (Arrays.asList(valueStrings).contains(o2))
return 1;
else
return 0;
}
Result:
Removed: orange
Removed: john
Removed: grape
Removed: test
Removed: blue
Removed: handle
Comparatoris broken, please consult its documentation (e.g. "Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.", "The implementor must ensure that signum(compare(x, y)) == -signum(compare(y, x)) for all x and y", ...)