Java的priorityQueue

import java.util.Comparator; 
import java.util.PriorityQueue; 
import java.util.Queue;

 public class myclass{  
    public static void main(String args[]) 
     { 
          Comparator<Emp> OrderIsdn =  new Comparator<Emp>(){ 
             public int compare(Emp o1, Emp o2) { 
                 
                float numbera = o1.getSal(); 
                   float numberb = o2.getSal(); 
                 if(numberb > numbera) 
                   { 
                      return 1; 
                   } 
                  else if(numberb<numbera) 
                  { 
                      return -1; 
                   } 
                  else 
                   { 
                     return 0; 
                   } 
                
              }       
               
        };  //end Comparator<Emp>
          Queue<Emp> priorityQueue =  new PriorityQueue<Emp>(11,OrderIsdn); 
             Emp t1 = new Emp("aa1","t1",1); 
          Emp t3 = new Emp("aa2","t3",3); 
          Emp t2 = new Emp("aa3","t2",2); 
          Emp t4 = new Emp("aa4","t4",0); 
          priorityQueue.add(t1); 
          priorityQueue.add(t3); 
           priorityQueue.add(t2); 
           priorityQueue.add(t4); 
           while(!priorityQueue.isEmpty())
           System.out.println(priorityQueue.poll().toString()); 
          
      }// end main

  } 

 class Emp {    
   private String name;    
   private float sal;    
   private String num;           
   public Emp(String num,String name,float sal)    
      {  this.num=num;   
         this.name=name;  
         this.sal=sal;    
      }                 
   public String getName() {  return name;   }      
   public void setName(String name) {   this.name = name; }   
   public float getSal() {  return sal;  }       
   public void setSal(float sal) {   this.sal = sal;   }       
   public String getNum() {   return num;  }       
   public void setNum(String num) {  this.num = num;  }
    public String toString() 
      { 
           return getName() + " - " + getSal() +" - "+getNum(); 
     }
 }

输出:

t3 - 3.0 - aa2
t2 - 2.0 - aa3
t1 - 1.0 - aa1
t4 - 0.0 - aa4

——————————————————————————————————

PriorityQueue仅仅保持了队列顶部元素总是最小,但内部的其它元素的顺序却随着元素的减少可能处于变化之中(原因在于add()的实现)。证明如下:

PriorityQueue<String> pq = new PriorityQueue<String>();
           pq.offer("a");
           pq.offer("b");
           pq.offer("c");
           pq.offer("d");
           pq.offer("e");           
           while (!pq.isEmpty()) {
              System.out.print("left:");
               for (String s : pq) {
                   System.out.print(s + " ");
               }
               System.out.println();
               System.out.println("poll(): " + pq.poll());
           }//end while

输出:

left:a b c d e
poll(): a
left:b d c e
poll(): b
left:c d e
poll(): c
left:d e
poll(): d
left:e
poll(): e

你可能感兴趣的:(Java的priorityQueue)