In: Computer Science
Write a java class for a Priority Queue. Use an arraylist, and include enque, deque, and a method to get all the values of the queue. (This is not writing a file implementing the java class PriorityQueue, but rather you are writing a program that is a priority queue).
COde:
//PriorityQueue.java
import java.util.*;
public class PriorityQueue
{
private ArrayList queueArray;
private ArrayList priorityArray;
//Constructor
public PriorityQueue()
{
queueArray=new ArrayList();
priorityArray=new
ArrayList();
}
//Adds the items in the queue list by using
priority
public <T> void add(T itemAdd,int
priorityAdd)
{
queueArray.add(itemAdd);
priorityArray.add(priorityAdd);
}
public boolean isEmpty()
{
return queueArray.size()==0;
}
public <T> T remove()
{
int max=0,maxPriority=0;
for(int
i=0;i<queueArray.size();i++)
{
int priority =
((Integer) priorityArray.get(i)).intValue();
if( priority>
maxPriority)
{
max=i;
maxPriority=priority;
}
}
priorityArray.remove(max);
return (T)
queueArray.remove(max);
}
public void Print()
{
for(int
i=0;i<queueArray.size();i++)
{
System.out.println(queueArray.get(i));
}
}
}
//PriorityDemo.java
public class PriorityDemo
{
public static void main(String args[])
{
//Define PriorityQueue's class
object is q
PriorityQueue q=new
PriorityQueue();
//Input values
System.out.println("Queue
Value:");
q.add("X", 10);
q.add("Y", 1);
q.add("Z", 3);
//printing Queue
q.Print();
//Removing value
System.out.println("Queue Value
after remove:");
q.remove();
q.Print();
}
}
Output: