java集合--PriorityQueue优先级队列使用方法

 优先级队列是不同于先进先出队列的另一种队列。每次从队列中取出的是具有最高优先权的元素。

  PriorityQueue是从JDK1.5开始提供的新的数据结构接口。

  如果不提供Comparator的话,优先队列中元素默认按自然顺序排列,也就是数字默认是小的在队列头,字符串则按字典序排列。

       由于网上的资料大多将优先级队列各个方法属性,很少有实例讲解的,为方便大家以后使用,我就写了个demo~

      如果想实现按照自己的意愿进行优先级排列的队列的话,需要实现Comparator接口。下面的方法,实现了根据某个变量,来进行优先级队列的建立。

  1. import java.util.Comparator;
  2. import java.util.PriorityQueue;
  3. import java.util.Queue;
  4. public class test {
  5. private String name;
  6. private int population;
  7. public test(String name, int population)
  8. {
  9. this.name = name;
  10. this.population = population;
  11. }
  12. public String getName()
  13. {
  14. return this.name;
  15. }
  16. public int getPopulation()
  17. {
  18. return this.population;
  19. }
  20. public String toString()
  21. {
  22. return getName() + " - " + getPopulation();
  23. }
  24. public static void main(String args[])
  25. {
  26. Comparator<test> OrderIsdn = new Comparator<test>(){
  27. public int compare(test o1, test o2) {
  28. // TODO Auto-generated method stub
  29. int numbera = o1.getPopulation();
  30. int numberb = o2.getPopulation();
  31. if(numberb > numbera)
  32. {
  33. return 1;
  34. }
  35. else if(numberb<numbera)
  36. {
  37. return - 1;
  38. }
  39. else
  40. {
  41. return 0;
  42. }
  43. }
  44. };
  45. Queue<test> priorityQueue = new PriorityQueue<test>( 11,OrderIsdn);
  46. test t1 = new test( "t1", 1);
  47. test t3 = new test( "t3", 3);
  48. test t2 = new test( "t2", 2);
  49. test t4 = new test( "t4", 0);
  50. priorityQueue.add(t1);
  51. priorityQueue.add(t3);
  52. priorityQueue.add(t2);
  53. priorityQueue.add(t4);
  54. System.out.println(priorityQueue.poll().toString());
  55. }

猜你喜欢

转载自blog.csdn.net/xyajia/article/details/80969509