我已经创建了一个优先级队列,并用项目填充队列,并使用此队列作为基础,我遍历它并找到项目的优先级。根据优先级,使用某种逻辑将项目移动到子队列。
在我的主程序中,我使用静态语句创建了有界子队列,我想要做的是使用我的父队列构造函数的构造函数创建有界子队列:public HiLoPriorityQueue(int high_capacity, int low_capacity)
构造函数应创建具有初始容量high_capacity的高优先级有界子队列和具有容量low_capacity的低优先级有界子队列
是否可以通过使用父队列上应用的相同添加和删除方法从父队列创建子队列?
我的主要计划:
public class PQTest {
public static void main(String[] args) {
HiLoPriorityQueue<Customer> prq = new HiLoPriorityQueue<Customer>(10);
Customer c1 = new Customer("Rock",999);
Customer c2 = new Customer("Brock",1);
Customer c3 = new Customer("UnderTaker",1000);
HiLoPriorityQueue<Customer> hq = new HiLoPriorityQueue<Customer>(5);
HiLoPriorityQueue<Customer> lq = new HiLoPriorityQueue<Customer>(3);
// insert values in the queue
prq.add(c1);
prq.add(c2);
prq.add(c3);
// create iterator from the queue
Iterator it = prq.iterator();
System.out.println ( "Priority queue values are: ");
while (it.hasNext()){
Customer c = (Customer) it.next();
System.out.println ( "Value: "+ c);
System.out.println("Priority is :: "+c.getPriority());
if(c.getPriority() == 1){
if(hq.size() < 5 )
hq.add(c);
else{
if(hq.size() < 5 ) lq.add(c);
else{
lq.remove();
lq.add(c);
}
}
}
else{
if(lq.size() < 3) lq.add(c);
}
}
}
}
队列创建类:
public class HiLoPriorityQueue<E extends BinaryPrioritizable> extends AbstractCollection{
private int count;
private Object[] elements;
private Object[] helements;
private Object[] lelements;
private int head;
private int tail;
public HiLoPriorityQueue(int high_capacity, int low_capacity){
helements = new Object[high_capacity];
lelements = new Object[low_capacity];
count = 0;
head = 0;
tail = 0;
}
public HiLoPriorityQueue(int capacity)
{
elements = new Object[capacity];
count = 0;
head = 0;
tail = 0;
}
@Override
public Iterator<E> iterator()
{
return new Iterator<E>()
{
public boolean hasNext()
{
return visited < count;
}
public E next()
{
int index = (head + visited) % elements.length;
E r = (E) elements[index];
visited++;
return r;
}
public void remove()
{
throw new UnsupportedOperationException();
}
private int visited = 0;
};
}
public boolean add(E anObject)
{
elements[tail] = anObject;
tail = (tail + 1) % elements.length;
count++;
return true;
}
public E remove()
{
E r = (E) elements[head];
head = (head + 1) % elements.length;
count--;
return r;
}
@Override
public int size()
{
return count;
}
}
答案 0 :(得分:0)
你的代码没什么意义。为什么使用Object[]
数组来保存HiLoPriorityQueue
类中的元素?使用Object
数组通常是一个坏主意,我认为根据您的类规范使用ArrayList<E extends BinaryPrioritizable>
会更有意义。其次,为什么你有helements
和lelements
因为它们从未被使用过?
是否可以通过使用父队列上应用的相同添加和删除方法从父队列创建子队列?
这个问题的答案是肯定的,因为您的父队列与您的子队列的类型相同。但我不完全确定这是你要求与否,我也不完全确定你要做什么。
但是,如果我理解正确,我认为您正在尝试保留低优先级队列和高优先级队列。这些应该放在HiLoPriorityQueue
类中,并在用户adds/removes
数据时在内部处理。您的优先级分离逻辑应该放在add()
类的HiLoPriorityQueue
方法中。
最后,如果您想要一个数据结构,以便在低优先级元素之前处理所有高优先级元素,您应该只使用内置MaxHeap
(即PirorityQueue<Customer> q = new PriorityQueue<Customer>()
)来指定比较器。
希望这会有所帮助。