question num 4 . java programming Thermostat t = new Thermostat(0, 100); t.setTe
ID: 3721030 • Letter: Q
Question
question num 4 . java programming
Thermostat t = new Thermostat(0, 100); t.setTemp(50); t.setTemp(150); t.setTemp(-50); // Should be OK. / Should throw TemperatureTooHigh exception. Il Should throw TemperatureToolLow exception. Write a gm to demend specifying the superclass catches the subclass exceptions. The order of exception handlers is important. If you try to catch a superclass exception type before a subclass type, the compiler would generate errors. Also show the re-throwing of exceptions. 4. Implement a priority queue capable of holding objects of an arbitrary type, T, by defining a Priorityoueue 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 inExplanation / Answer
Given below is the code for the question.
To indent code in eclipse , select code by pressing ctrl+a and then indent using ctrl+i
Please do rate the answer if it was helpful. Thank you
PriorityQueue.java
-------------------
import java.util.ArrayList;
public class PriorityQueue<T> {
class QNode
{
T item;
int priority;
QNode(T it, int pri)
{
item = it;
priority = pri;
}
}
private ArrayList<QNode> queue;
public PriorityQueue()
{
queue = new ArrayList<QNode>();
}
public boolean isEmpty()
{
return queue.isEmpty();
}
public int size()
{
return queue.size();
}
public void add(T item, int priority)
{
QNode qn = new QNode(item, priority);
int index = 0;
while(index < queue.size())
{
if(priority > queue.get(index).priority)
break;
index++;
}
queue.add(index, qn);
}
public T remove()
{
if(queue.isEmpty())
return null;
else
return queue.remove(0).item;
}
public String toString()
{
String s = "";
if(!queue.isEmpty())
{
QNode qn = queue.get(0);
s += qn.item.toString() + "{" + qn.priority +"}";
for(int i = 1; i < queue.size(); i++)
{
qn = queue.get(i);
s += ", " + qn.item.toString() + "{" + qn.priority +"}";
}
}
return s;
}
}
TestPriorityQueue.java
--------------------
public class TestPriorityQueue {
public static void main(String[] args) {
PriorityQueue<String> q = new PriorityQueue<String>();
q.add("X", 10);
q.add("Y", 1);
q.add("Z", 3);
System.out.println("Priority queue contains: " + q);
System.out.println(q.remove());
System.out.println(q.remove());
System.out.println(q.remove());
System.out.println("Priority queue contains: " + q);
}
}
output
-----
Priority queue contains: X{10}, Z{3}, Y{1}
X
Z
Y
Priority queue contains:
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.