具有复杂枚举的优先级队列?
我正在用 Java 编写一个代理,它从程序中的各种其他对象接收对其服务的请求。限制是一次只能完成一个进程,这意味着 PriorityQueue 可能是表示对其服务的请求的最佳方式。
不幸的是,这些进程被存储为具有许多不同状态的枚举。有没有一种简单的方法可以编写比较器以按照我想要的方式对这些状态进行排序?也就是说,
public enum AgentProcess
{
ACTION1, ACTION2, ACTION3, ACTION4, ACTION20
}
对于一些比较器,
public class ProcessComparator<Process>
{
public int compare(Process a, Process b)
{
//some arbitrary ordering of the processes, e.g., ACTION3 > ACTION19 > ACTION4...
}
}
我目前一直在做类似的事情,
public static int getValue(Process p)
{
switch(p)
case ACTION1:
return 5;
case ACTION2:
return 29;
case ACTION3:
return 18;
//etc
}
有没有一种方法可以重写我的枚举,使其自然排序,而不必为每个比较器定义权重或开关?
I am writing an Agent in Java that receives requests for its services from various other objects in the program. The restriction is that only one process can be done at once, which means that a PriorityQueue is probably the best way to represent requests for its services.
Unfortunately, these processes are stored as a enum with many different states. Is there an easy way to write a Comparator to order these states in the way I want? That is,
public enum AgentProcess
{
ACTION1, ACTION2, ACTION3, ACTION4, ACTION20
}
with some Comparator
public class ProcessComparator<Process>
{
public int compare(Process a, Process b)
{
//some arbitrary ordering of the processes, e.g., ACTION3 > ACTION19 > ACTION4...
}
}
I'm currently stuck with doing something like
public static int getValue(Process p)
{
switch(p)
case ACTION1:
return 5;
case ACTION2:
return 29;
case ACTION3:
return 18;
//etc
}
Is there a way I could rewrite my enum so that it is naturally ordered, without having to define weights or a switch for each?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想到了三种解决方案:
Three solutions come to my mind:
为了扩展 msell 的答案#3(保留列表并使用 indexOf 来计算排序顺序),这在强烈推荐(至少对我来说)中非常简单 Guava 库,使用
Ordering
类:非常好,恕我直言。
To expand on msell's answer #3 (keeping a list and using an indexOf to work out the sort order), this is trivially easy in the highly-recommended (at least by me) Guava library, using the
Ordering
class:Very nice, IMHO.
从 http://download.oracle.com/javase/tutorial/ 无耻地窃取java/javaOO/enum.html
整洁,我从来没有想过我会看到任何语言中附加到枚举的成对浮点数。 :)
Stolen shamelessly from http://download.oracle.com/javase/tutorial/java/javaOO/enum.html
Neat, I never thought I'd see pairs of floats attached to enums in any language. :)