我如何让一个PriorityQueue对我想要它排序的东西进行排序?

另外,在提供和添加方法之间有区别吗?


当前回答

在这里,我们可以定义用户定义的比较器:

以下代码:

 import java.util.*;
 import java.util.Collections;
 import java.util.Comparator; 


 class Checker implements Comparator<String>
 {
    public int compare(String str1, String str2)
    {
        if (str1.length() < str2.length()) return -1;
        else                               return 1;
    }
 }


class Main
{  
   public static void main(String args[])
    {  
      PriorityQueue<String> queue=new PriorityQueue<String>(5, new Checker());  
      queue.add("india");  
      queue.add("bangladesh");  
      queue.add("pakistan");  
 
      while (queue.size() != 0)
      {
         System.out.printf("%s\n",queue.remove());
      }
   }  
}  

输出: 印度 巴基斯坦 孟加拉国

提供和添加方法的区别:链接

其他回答

使用构造函数重载,它接受Comparator<?super E>比较器,并传入一个比较器,它会按照排序顺序进行比较。如果你给出一个你想要如何排序的例子,如果你不确定的话,我们可以提供一些示例代码来实现比较器。(其实很简单。)

正如在其他地方所说:offer和add只是不同的接口方法实现。在JDK源代码中,添加calls offer。虽然add和offer通常具有潜在的不同行为,因为offer能够表示由于大小限制而不能添加值,但这种差异在PriorityQueue中是无关的,因为PriorityQueue是无界的。

下面是一个优先级队列按字符串长度排序的例子:

// Test.java
import java.util.Comparator;
import java.util.PriorityQueue;

public class Test {
    public static void main(String[] args) {
        Comparator<String> comparator = new StringLengthComparator();
        PriorityQueue<String> queue = new PriorityQueue<String>(10, comparator);
        queue.add("short");
        queue.add("very long indeed");
        queue.add("medium");
        while (queue.size() != 0) {
            System.out.println(queue.remove());
        }
    }
}

// StringLengthComparator.java
import java.util.Comparator;

public class StringLengthComparator implements Comparator<String> {
    @Override
    public int compare(String x, String y) {
        // Assume neither string is null. Real code should
        // probably be more robust
        // You could also just return x.length() - y.length(),
        // which would be more efficient.
        if (x.length() < y.length()) {
            return -1;
        }
        if (x.length() > y.length()) {
            return 1;
        }
        return 0;
    }
}

输出如下:

短 媒介 确实很长

从队列API:

offer方法尽可能插入一个元素,否则返回false。这与合集不同。方法,该方法只能通过抛出未经检查的异常来添加元素。offer方法设计用于故障是正常情况,而不是异常情况,例如在固定容量(或“有界”)队列中。

在这里,我们可以定义用户定义的比较器:

以下代码:

 import java.util.*;
 import java.util.Collections;
 import java.util.Comparator; 


 class Checker implements Comparator<String>
 {
    public int compare(String str1, String str2)
    {
        if (str1.length() < str2.length()) return -1;
        else                               return 1;
    }
 }


class Main
{  
   public static void main(String args[])
    {  
      PriorityQueue<String> queue=new PriorityQueue<String>(5, new Checker());  
      queue.add("india");  
      queue.add("bangladesh");  
      queue.add("pakistan");  
 
      while (queue.size() != 0)
      {
         System.out.printf("%s\n",queue.remove());
      }
   }  
}  

输出: 印度 巴基斯坦 孟加拉国

提供和添加方法的区别:链接

只需将适当的Comparator传递给构造函数:

PriorityQueue(int initialCapacity, Comparator<? super E> comparator)

offer和add之间的唯一区别是它们所属的接口。offer属于Queue<E>接口,而add最初出现在Collection<E>接口。除此之外,这两种方法做的事情完全相同——将指定的元素插入优先级队列。

Priority Queue has some priority assigned to each element, The element with Highest priority appears at the Top Of Queue. Now, It depends on you how you want priority assigned to each of the elements. If you don't, the Java will do it the default way. The element with the least value is assigned the highest priority and thus is removed from the queue first. If there are several elements with the same highest priority, the tie is broken arbitrarily. You can also specify an ordering using Comparator in the constructor PriorityQueue(initialCapacity, comparator)

示例代码:

PriorityQueue<String> queue1 = new PriorityQueue<>();
queue1.offer("Oklahoma");
queue1.offer("Indiana");
queue1.offer("Georgia");
queue1.offer("Texas");
System.out.println("Priority queue using Comparable:");
while (queue1.size() > 0) {
    System.out.print(queue1.remove() + " ");
}
PriorityQueue<String> queue2 = new PriorityQueue(4, Collections.reverseOrder());
queue2.offer("Oklahoma");
queue2.offer("Indiana");
queue2.offer("Georgia");
queue2.offer("Texas");
System.out.println("\nPriority queue using Comparator:");
while (queue2.size() > 0) {
    System.out.print(queue2.remove() + " ");
}

输出:

Priority queue using Comparable:
Georgia Indiana Oklahoma Texas 
Priority queue using Comparator:
Texas Oklahoma Indiana Georgia 

除此之外,你还可以定义Custom Comparator:

import java.util.Comparator;

public class StringLengthComparator implements Comparator<String>
{
    @Override
    public int compare(String x, String y)
    {
        //Your Own Logic
    }
}