Hi, I need help with the following java problem. Any sugessions solutions? Immpl
ID: 3553766 • Letter: H
Question
Hi, I need help with the following java problem. Any sugessions solutions?
Immplement a priority queue capable of holding objects of an arbitrary type, T , by
defining a PriorityQueue class that implements the queue with an ArrayList .
A priority queue is a type of list where every item added to the queue also has an
associated priority. Define priority in your application so that those items with the
largest numerical value have the highest priority. Your class should support the
following methods:
Explanation / Answer
import java.util.*;
public class PriorityQueue {
private class Item {
public Object value;
public int priority;
public Item(Object obj, int pr) {
value = obj;
priority = pr;
}
}
private int mySize;
private ArrayList<Item> myList;
public PriorityQueue() {
myList = new ArrayList<Item>(32);
mySize = 0;
}
public boolean add(Object o, int priority) {
Item item = new Item(o, priority);
int i;
for(i=0; i<mySize; i++) {
if(myList.get(i).priority < priority) {
break;
}
}
myList.add(i, item);
mySize++; // added element, update count
return true;
}
public Object remove() {
if (mySize != 0) {
Item hold = myList.get(0);
myList.remove(0); // pop last off
mySize--;
return hold.value;
}
return null;
}
public static void main(String args[]) {
PriorityQueue pq = new PriorityQueue();
pq.add("X", 10);
pq.add("Y", 1);
pq.add("Z", 3);
System.out.println(pq.remove()); // Returns X
System.out.println(pq.remove()); // Returns Z
System.out.println(pq.remove()); // Returns Y
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.