我對 PriorityQueue 感到困惑,不確定我的用例是否有不同的方法。
我不想比較兩個字串,而是想將傳入的字串與 String[] 進行比較。
它有點作業,但頭節點不會移動。
主要的:
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());
}
}
}
比較類:
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;
}
}
結果:
Removed: test
Removed: john
Removed: orange
Removed: blue
Removed: handle
Removed: grape
值“test”始終排在第一位,即使它不在 String[] 中也是如此。其他值的順序似乎是正確的,因為“john”和“orange”在 String[] 中,而其余的則不是。
問題是什么,這是實作我的用例的正確方法嗎?
編輯:我也試過這個
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;
}
結果如下:
Removed: orange
Removed: handle
Removed: grape
Removed: test
Removed: blue
Removed: john
橙色在正確的位置 by john 在底部,當它應該在橙色之后
新編輯:根據評論重新閱讀檔案后,我設法以這種方式實作了一個作業版本。可能會添加@Progman else 回傳。
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;
}
結果:
Removed: orange
Removed: john
Removed: grape
Removed: test
Removed: blue
Removed: handle
uj5u.com熱心網友回復:
您的compare()方法沒有檢查兩個String進入的物件。這使得當您只看一個字串時很難比較兩個字串。此外,您的compare()方法在某種意義上是不對稱的sgn(compare(x,y)),與https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html中定義的-sgn(compare(y,x))(注意)不同比較-TT-。這使得.-StringPriorityQueue
當你想要某種String在開頭排序的“VIP”串列時,你必須檢查該compare(x, y)方法的幾種情況:
x是“VIP”值,但y不是。x是“VIP”值以及y.x不是“VIP”值,而是y。x不是“VIP”值,也不是y。
特別地,當值都是“VIP”值或都不是“VIP”值時,您仍然必須為這些字串回傳一個合理的比較值。該方法是首先處理一個值在“VIP”串列中而另一個不在的情況。之后,像往常一樣使用 比較字串String.compareTo()。該方法可能如下所示:
public int compare(String o1, String o2) {
if (valueStringsList.contains(o1) &&
!valueStringsList.contains(o2)) {
return -1; // only o1 is a "VIP"
}
if (!valueStringsList.contains(o1) &&
valueStringsList.contains(o2)) {
return 1; // only o2 is a "VIP"
}
return o1.compareTo(o2); // normal sorting
}
(您可能需要交換1和-1)
uj5u.com熱心網友回復:
邏輯關閉了。如果兩者都存在或都不存在,則您需要回傳 0。這是實作這一目標的一種方法:
public int compare(String o1, String o2) {
List<String> list = Arrays.asList(valueStrings);
boolean found1 = list.contains(o1);
boolean found2 = list.contains(o2);
return found1 == found2 ? 0 : found1 ? -1 : 1;
}
或者,您可以從 lambda 構造一個比較器,而不是手動實作它:
Comparator.comparing(Arrays.asList(valueStrings)::contains).reversed()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/537213.html
標籤:爪哇优先队列
