Java PriorityQueue implementation

PriorityQueue Queue

PriorityQueue extends AbstactQueue. PriorityQueue is a type of queue but not provide the FIFO facility to its elements. It not allows the null elements. A PriorityQueue is like a normal queue but each element has a priority associated with it.

Example

package com.w3spoint;
 
public class Test {
    @SuppressWarnings("rawtypes")
    private Comparable[] pQueue;
    private int index;
 
    public Test(int capacity){
        pQueue = new Comparable[capacity];
    }
 
    public void insert(Comparable item ){
        if(index == pQueue.length){
            System.out.println("Overflow state.");
            return;
        }
        pQueue[index] = item;
        index++;
        System.out.println("Adding element: "+item);
    }
 
    @SuppressWarnings("unchecked")
    public Comparable remove(){
        if(index == 0){
            System.out.println("Underflow state.");
            return null;
        }
        int maxIndex = 0;
        for (int i=1; i<index; i++) { 
            if (pQueue[i].compareTo (pQueue[maxIndex]) > 0) { 
                maxIndex = i; 
            } 
        } 
        Comparable result = pQueue[maxIndex]; 
        System.out.println("removing: "+result);
        index--; 
        pQueue[maxIndex] = pQueue[index]; 
        return result;
    }
 
	public static void main(String args[]){
		try {
			Test pQueue = new Test(3);
			pQueue.insert(15);
			pQueue.insert(8);
			pQueue.insert(12);
			pQueue.remove();
			pQueue.remove();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

Adding element: 15
Adding element: 8
Adding element: 12
removing: 15
removing: 12
Content Protection by DMCA.com
Please Share