gpt4 book ai didi

java - java中优先级队列的比较器

转载 作者:太空宇宙 更新时间:2023-11-04 11:22:12 25 4
gpt4 key购买 nike

我尝试使用优先级队列的覆盖比较器方法,我想实现以下目标:

我有当前列表:

RG3

PR1

PR2

RG4

RG1

RG2

RG指普通人,PR指优先人,数字代表轮次。我想要的是获得先进先出的顺序,除非优先人员会轮到队列的顶部。所以在列表中我想要以下结果

PR1

PR2

RG1

RG2

RG3

RG4

这是我到目前为止所做的事情:

Queue<Ficha> cola = new PriorityQueue<>(6, idComparator);


while (!list.isEmpty()) //this list is the unsorted list.
{
aux = list.remove(0);

cola.add(aux); // adds it to the priority queue

}

while(!cola.isEmpty())
{
aux = cola.poll();
System.out.println(aux.getCod_priority()+aux.getTurn()); // this shows me the order of the queue
}


}

public static Comparator<Ficha> idComparator = new Comparator<Ficha>()
{

@Override
public int compare(Ficha f1, Ficha f2) {
return (int) ((f1.getTurn()+prioridad(f1.getCod_priority())) - (f2.getTurn()+prioridad(f2.getCod_priority())));
}
};


private static long prioridad(String cod_priority) // this method i use it to give the cod_priority a int value to compare
{
if(cod_tipo_ficha=="PR")
{
return 10000;
}
else
{
return 1;
}
}

当我运行它时,我得到以下命令:

PR1

RG1

RG2

PR2

RG3

RG4

我知道我的问题出在比较器方法中,但我不知道如何实现我想要的队列。

我知道有很多与如何比较相关的问题,但我看到的唯一答案是当您比较字符串时。这个我需要比较优先级字符串和整数。

最佳答案

只需将 cod_tipo_ficha=="PR"更改为

if("PR".equals(cod_tipo_ficha)) {
...
}

应该可以

关于java - java中优先级队列的比较器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44773693/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com