Я пытаюсь построить Приоритетную Очередь, изменяя мою ранее реализованную Очередь, которая принимает дженерики.Я создаю класс с именем Priority Queue (который принимает дженерики), который расширяет мой класс Queue (который принимает дженерики).Последний класс - основной фокус, очередь .Я подталкиваю клиента в своих тестах, и когда я получаю этого клиента в моем методе push очереди, я хочу использовать его, чтобы сравнить его приоритет с приоритетом другого клиента в моей очереди.Любые предложения по подходу к этому будут полезны, но мой вопрос в том, как мне получить доступ к 3 полям моего объекта customer (или val in push) из очереди?
У меня есть тестовый класс, который проверяет,компараторы работают.Я также настроил тестовые случаи, чтобы я мог убедиться, что моя очередь с приоритетами работает, когда я ее реализую.
Мой класс для проверки, работают ли мои компараторы и работает ли моя очередь приоритетов, когда она реализована:
public class TestCustomer {
public static void main(String args[]) {
Customer customer1 = new Customer(3000, 20, 5);
Customer customer2 = new Customer(5000, 15, 7);
Customer customer3 = new Customer(5000, 20, 5);
Customer customer4 = new Customer(3000, 3, 5);
Customer customer5 = new Customer(3000, 3, 8);
// comparator test
Customer.WorthComparator worth = new Customer.WorthComparator();
Customer.LoyaltyComparator loyal = new Customer.LoyaltyComparator();
Customer.WorthPoliteComparator polite = new Customer.WorthPoliteComparator();
assert worth.compare(customer1, customer2) == -1;
assert worth.compare(customer2, customer3) == 0;
assert worth.compare(customer2, customer1) == 1;
assert loyal.compare(customer1, customer2) == 1;
assert loyal.compare(customer2, customer1) == -1;
assert loyal.compare(customer1, customer3) == 0;
assert polite.compare(customer3, customer2) == -1;
assert polite.compare(customer2, customer3) == 1;
assert polite.compare(customer1, customer2) == -1;
assert polite.compare(customer2, customer3) == 1;
assert polite.compare(customer1, customer4) == 0;
// priority queue test
PriorityQueue<Customer> pQueueW = new PriorityQueue<Customer>(worth);
PriorityQueue<Customer> pQueueL = new PriorityQueue<Customer>(loyal);
PriorityQueue<Customer> pQueueP = new PriorityQueue<Customer>(polite);
// push -- type T, pass in a val // judgement upon worth
//PUSH customers for Worth
pQueueW.push(customer1);
pQueueW.push(customer2);
pQueueW.push(customer4);
assert pQueueW.pop() == customer2;
//PUSH customers for Loyalty
pQueueL.push(customer1);
pQueueL.push(customer2);
pQueueL.push(customer3);
assert pQueueL.pop() == customer1;
//PUSH customers for Polite
pQueueP.push(customer2);
pQueueP.push(customer4);
pQueueP.push(customer5);
assert pQueueP.pop() == customer2;
assert pQueueP.pop() == customer5;
//
}
}
Мой класс очереди приоритетов просто расширяет очередь и использует свою функцию push.Мне нужно будет создать метод для вызова моего всплывающего окна в очереди:
import java.util.Comparator;
public class PriorityQueue<T> extends Queue<T>
{
Comparator<T> compare;
public PriorityQueue(Comparator<T> comp)
{
compare = comp;
}
//@Override
public void push(T val)
{
super.push(val); //right now this is just a normal Queue as it will do what its parent did.
}
В моем классе клиентов есть конструктор для создания клиентов.Здесь также используются мои различные компараторы для создания порядка клиентов:
import java.util.Comparator;
public class Customer
{
int netWorth;
int yearsWithCompany;
int politeness;
public Customer(int netWorth,int yearsWithCompany,int politeness)
{
this.netWorth = netWorth;
this.yearsWithCompany = yearsWithCompany;
this.politeness = politeness;
}
/**
compares clients based on thier net worth
*/
public static class WorthComparator implements Comparator<Customer>
{
*/
public int compare(Customer c1, Customer c2)
{
int net1 = c1.netWorth;
int net2 = c2.netWorth;
if (net1 == net2) {
return 0;
}
else if (net1 < net2) {
return -1;
}
else {
return 1;
}
}
}
/**
compares clients based on thier loyalty
*/
public static class LoyaltyComparator implements Comparator<Customer>
{
/**
*/
public int compare(Customer c1, Customer c2)
{
int years1 = c1.yearsWithCompany;
int years2 = c2.yearsWithCompany;
if (years1 == years2) {
return 0;
}
else if (years1 < years2) {
return -1;
}
else {
return 1;
}
}
}
/**
compares clients based on thier net worth.
If there is a tie, politeness is used.
*/
public static class WorthPoliteComparator implements Comparator<Customer>
{
/**
*/
public int compare(Customer c1, Customer c2)
{
if (c1.netWorth == c2.netWorth)
{
if (c1.politeness < c2.politeness) {
return -1;
}
else if (c1.politeness > c2.politeness) {
return 1;
}
else {
return 0;
}
}
else if (c1.netWorth > c2.netWorth){
//int politeness = WorthComparator.compare(c1, c2);
//return politeness;
return 1;
}
else {
return -1 ;
}
}
}
}
Мой класс очереди был реализован для работы в качестве обычной очереди.Сейчас я модифицирую его, чтобы превратить его в очередь с приоритетами.Класс Queue ниже: public class Queue {
public class QNode<T> {
private QNode<T> node;
private T val;
public QNode(QNode<T> node, T val) {
this.node = node;
this.val = val;
}
}
protected QNode<T> head;
protected QNode<T> rear;
protected QNode<T> temp;
public Queue()
{
head = null;
rear = null;
}
public void push(T val) // T = Customer type -- val is a customer
{
// if I wanted to get the contents out of val, which is a customer
// who has a net worth, years loyal, and politeness
// how would I access let's say, the netWorth from val?
// first node created
if (head == null && rear == null){
head = new QNode<T>(rear, val);
rear = head;
}
}
public T pop()
{
if (head == null){
throw new QueueUnderFlowException();
}
else if(head == rear) {
T temp_hold = head.val;
head = null;
rear = null;
return temp_hold;
}
else {
T oldN = head.val;
this.head = this.head.node;
return oldN;
}
}
/**
returns true if the queue is empty
*/
public boolean isEmpty()
{
if (head == null) {
return true;
}
else {
return false;
}
}
}