April 4, 2011

Java Collections Framework: PriorityQueue Example

package info.icontraining.collections;

import java.util.*;

public class PriorityQueueExample {

   public static void main(String args[]) {

      Queue<Test> queue = new PriorityQueue<Test>();
  
      queue.offer(new Test(3));
      queue.offer(new Test(1));
      queue.offer(new Test(2));
  
      while (queue.size()!= 0) {
         System.out.println(queue.poll().getPriority());
      }
   }
}

class Test implements Comparable<Test> {
   private int priority;
 
   public Test(int priority) {
      this.priority = priority;
   }

   public int compareTo(Test o) {
      if (this.priority < o.priority)
         return -1;
      else if (this.priority > o.priority)
         return 1;
      return 0;
   }
 
   public int getPriority() {
      return this.priority;
   }
}

No comments:

Post a Comment