我正在做一个课堂作业,我不太明白如何按照作业要求的方式使用比较器。
作业内容如下:
"完成优先队列类
- 您的优先级队列必须使用匿名函数来决定优先级
- 它必须将 Function 接口作为构造函数的参数
- 您仍然应该拥有默认构造函数——如果没有提供函数,请使用类的 compareTo 函数”
这是我正在学习的课程...
public class PriorityQueue <Item extends Comparable<Item>> {
public PriorityQueue()
{
}
public PriorityQueue(Comparator<Item> compare )
{
}
private int size = 0;
private Node<Item> head = null;
private Comparator<Item> compare ;
private static class Node<Item>
{
private Item data;
private Node<Item> next;
public Node(Item data, Node<Item> next)
{
this.data = data;
this.next = next;
}
public Node(Item data)
{
this.data = data;
this.next = null;
}
public Node()
{
this.data = null;
this.next = null;
}
}
@Override
public int size() {
return size;
}
@Override
public Item dequeue() {
// TODO Auto-generated method stub
return null;
}
@Override
public void enqueue(Item item) {
Node<Item> curr = head;
Node<Item> prev = curr;
if (isEmpty())
{
head = new Node<Item>(item,null);
}
else
{
while (curr != null)
{
prev = curr;
curr = curr.next;
}
prev.next = new Node<Item>(item, curr);
}
size++;
}
@Override
public boolean isEmpty() {
return size == 0;
}
@Override
public void printQueue() {
Node<Item> curr = head;
while (curr != null)
{
System.out.println(curr.data);
curr = curr.next;
}
}
}
这是队列将包含的进程类...
public class Process implements Comparable<Process> {
private ProcessPriorty priority;
private String name;
public Process(ProcessPriorty priority, String name) {
super();
this.priority = priority;
this.name = name;
}
public void setPriority(ProcessPriorty priority) {
this.priority = priority;
}
@Override
public String toString() {
return name + "... Priority = " + priority + ".";
}
public String getName() {
return name;
}
public ProcessPriorty getPriority() {
return priority;
}
@Override
public int compareTo(Process other) {
if(other == null)
{
return 1;
}
return this.priority.compareTo(other.priority) ;
}
}
我了解队列的概念,甚至将 enqueue 方法编码为一个简单的队列,在项目进入时插入它们。我遇到的问题是比较该方法中的节点,以便在插入时按优先级对列表进行排序. 我认为这与作业的这三个方向有关。那么,我应该如何处理构造函数、Comparator 变量以及如何使其默认为 compareTo?